c# - Lazy<T> 延迟加载错误 : A field initializer cannot reference the non-static field, 方法或属性

标签 c# .net generics lazy-loading

我第一次尝试使用延迟加载来初始化我的类中的进度对象。但是,我收到以下错误:

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/

相关文章:

C# I/O 异常 "This machine is disabled for file encryption.\r\n"

Java:集合中的接口(interface)未被识别为参数

c# - 自定义 Json.NET 转换器不应序列化属性

c# - 使用 nHibernate 忽略实体类型的方法

c# - EF Fluent api poco 使用现有 Db 生成和映射

C# 从基类列表访问继承的类属性

c# - 使用 Rhino 模拟从 Spring.Net 模拟 TransactionTemplate

c# - 使用正则表达式替换引号外的空格

C# 在不知道特定类型的情况下访问泛型方法

java - 通用接口(interface)实现不起作用