经由Lazy T访问非静态成员.或任何lambda表达式 [英] Accessing a non-static member via Lazy<T> or any lambda expression

查看:86
本文介绍了经由Lazy T访问非静态成员.或任何lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

public class MyClass
{
    public int X { get; set; }
    public int Y { get; set; }

    private Lazy<int> lazyGetSum = new Lazy<int>(new Func<int>(() => X + Y));
    public int Sum{ get { return lazyGetSum.Value; } }

}

给我这个错误:

字段初始化器无法引用非静态字段,方法或 属性.

A field initializer cannot reference the non-static field, method, or property.

我认为通过惰性访问非静态成员是非常合理的,该怎么做?

I think it is very reasonable to access a non-static member via lazy, how to do this?

*编辑*

已接受的答案可以完美地解决问题,但是要一如既往地详细,深入地了解问题的原因,您可以阅读 Joe Skeet的答案.

The accepted answer solves the problem perfectly, but to see the detailed and in-depth -as always- reason of the problem you can read Joh Skeet's answer.

推荐答案

您可以将其移至构造函数中:

You can move it into constructor:

private Lazy<int> lazyGetSum;
public MyClass()
{
   lazyGetSum = new Lazy<int>(new Func<int>(() => X + Y));
}

有关问题原因的更多详细信息,请参见下面的@JohnSkeet答案. 通过Lazy< T>访问非静态成员或任何lambda表达式

See @JohnSkeet answer below for more details about the reason of the problem. Accessing a non-static member via Lazy<T> or any lambda expression

这篇关于经由Lazy T访问非静态成员.或任何lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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