为什么C#lambda表达式不能使用实例属性和字段?

编程入门 行业动态 更新时间:2024-10-20 07:45:01
本文介绍了为什么C#lambda表达式不能使用实例属性和字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么在类范围中使用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表达式不能使用实例属性和字段?

本文发布于:2023-11-08 07:36:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568750.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   字段   实例   属性   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!