我第一次尝试使用延迟加载来初始化我的类中的进度对象。但是,我收到以下错误:
A field initializer cannot reference the non-static field, method, or property.
private Lazy<Progress> m_progress = new Lazy<Progress>(() =>
{
long totalBytes = m_transferManager.TotalSize();
return new Progress(totalBytes);
});
在 .NET 2.0 中,我可以执行以下操作,但我更愿意使用更新的方法:
private Progress m_progress;
private Progress Progress
{
get
{
if (m_progress == null)
{
long totalBytes = m_transferManager.TotalSize();
m_progress = new Progress(totalBytes);
}
return m_progress;
}
}
有人能帮忙吗?
非常感谢。
最佳答案
该初始化程序需要将 this
传递到捕获类中,而 this
不能从字段初始化程序获得。但是,它在构造函数中可用:
private readonly Lazy<Progress> m_progress;
public MyType()
{
m_progress = new Lazy<Progress>(() =>
{
long totalBytes = m_transferManager.TotalSize();
return new Progress(totalBytes);
});
}
不过,就我个人而言,我只会使用 get
访问器;p
关于c# - Lazy<T> 延迟加载错误 : A field initializer cannot reference the non-static field, 方法或属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11828780/