为什么在类范围中使用C#lambda表达式不能使用实例属性和字段?参见以下示例:
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 }; ... }为什么不允许这样做?
编辑
如果可以的话:
public class Point:INotifyPropertyChanged { public float X {get; set;} public float Y {get; set;} PropertyChangedEventHandler onPointsPropertyChanged; public Point() { onPointsPropertyChanged = (_, e) => { X = 5; Y = 5; }; } ... }为什么我们不能像类范围内的其他字段一样初始化onPointsPropertyChanged ?,例如:int a = 5.始终在构造函数执行后使用字段onPointsPropertyChanged.
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.
推荐答案
字段初始化器无法引用非静态字段,方法或属性...
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.
更改初始化以在类构造函数中设置lambda函数:
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; }; } }更多推荐
为什么C#lambda表达式不能使用实例属性和字段?
发布评论