为什么C#lambda表达式不能使用实例属性和字段? [英] Why C# lambda expression can't use instance properties and fields?

查看:235
本文介绍了为什么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表达式不能使用实例属性和字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆