为什么C#lambda表达式在类范围内使用时不能使用实例属性和字段?看这个例子:
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
};
...
}
Run Code Online (Sandbox Code Playgroud)
为什么不允许这样做?
编辑
如果我们能做到:
public class Point:INotifyPropertyChanged
{
public float X {get; set;}
public float Y {get; set;}
PropertyChangedEventHandler onPointsPropertyChanged;
public Point()
{
onPointsPropertyChanged = (_, e) =>
{
X = 5;
Y = 5;
};
}
...
}
Run Code Online (Sandbox Code Playgroud)
为什么我们不能onPointsPropertyChanged像类范围内的其他字段一样初始化?,对于instancie : int a = 5. onPointsPropertyChanged始终将在构造函数执行后使用该字段.
字段初始值设定项不能引用非静态字段,方法或属性...
字段初始值设定项在构造函数执行之前执行.在执行构造函数之前,不允许引用任何字段或属性.
更改初始化以在类构造函数中设置lambda函数:
public class Point : INotifyPropertyChanged
{
public float X { get; set; }
public float Y { get; set; }
PropertyChangedEventHandler onPointsPropertyChanged;
public Point()
{
onPointsPropertyChanged = (_, e) =>
{
X = 5;
Y = 5;
};
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1896 次 |
| 最近记录: |