Why C# lambda expression can't use instance pr

2020-07-13 11:40发布

问题:

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.

回答1:

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;
    };
  }
}


回答2:

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:

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?



标签: c# lambda scope