Why C# lambda expression can't use instance pr

2020-07-13 11:31发布

Why C# lambda expression can't use instance properties and fields, when is used in a class scope? See this example:

public class Point:INotifyPropertyChanged
{
    public float X {get; set;}
    public float Y {get; set;}

    PropertyChangedEventHandler onPointsPropertyChanged =  (_, e)  =>
                               {
                                   X = 5;
                                   Y = 5; //Trying to access instace properties, but a compilation error occurs
                               };
    ...
}

Why this is not allowed?

EDIT

If we can do:

public class Point:INotifyPropertyChanged
{
    public float X {get; set;}
    public float Y {get; set;}

    PropertyChangedEventHandler onPointsPropertyChanged; 
    public Point()
    {
        onPointsPropertyChanged =  (_, e)  =>
                               {
                                   X = 5;
                                   Y = 5;    
                               };
    }
    ...
}

Why we can't initialize onPointsPropertyChanged like a other fields inside the class scope?, for instancie: int a = 5. The field onPointsPropertyChanged always will be used after the constructor execute.

标签: c# lambda scope
3条回答
Evening l夕情丶
2楼-- · 2020-07-13 12:18

You cannot access an object instance before its constructor runs (such as in a field initializer or base constructor call).

This is true both inside a lambda and outside a lambda.

C# < 4 had a bug that allowed this in certain cases.

查看更多
叛逆
3楼-- · 2020-07-13 12:23

What instance are you referring to? At the point where you are creating the lambda expression, no instance has yet been created; so what instance would those calls to X and Y be bound to?

查看更多
Emotional °昔
4楼-- · 2020-07-13 12:24

A field initializer cannot reference the non-static field, method, or property ...

Field initializers are executed before the constructor is executed. You're not permitted to reference any fields or properties before the constructor is executed.

Change your initialization to set the lambda function in your classes contructor:

public class Point : INotifyPropertyChanged
{
  public float X { get; set; }
  public float Y { get; set; }

  PropertyChangedEventHandler onPointsPropertyChanged;

  public Point()
  {
    onPointsPropertyChanged = (_, e) =>
    {
      X = 5;
      Y = 5;
    };
  }
}
查看更多
登录 后发表回答