0

我有一个包含 5-6 个字段的类,应该在构造函数运行后初始化一次。

 public OriginalFileProcessor(IConfigManager configManager)
        {
            this._configManager = configManager;
            this._field1 = this._configManager.GetAppSetting<int>ConfigKeys.Key1);
            this._field2 = this._configManager.GetAppSetting<int>ConfigKeys.Key2);
            this._field3 = this._configManager.GetAppSetting<int>ConfigKeys.Key3);
            this._field4 = this._configManager.GetAppSetting<int>ConfigKeys.Key4);
            this._field5 = this._configManager.GetAppSetting<int>ConfigKeys.Key5);
        }

但除了构造函数中的简单赋值之外,我不喜欢编写逻辑。

例如,我不能对 field1 使用内联初始化,从那时起我就不能在那里使用 _configManager 实例:

private int readonly _field1 = this._configManager.GetAppSetting<int>ConfigKeys.Key1);

如果我使用只读属性,那么我必须添加额外的代码,如下所示:

  private int? _field1;
        public int Property1
        {
            get
            {
                if (!this._field1.HasValue)
                {
                    this.__field1 = this._configManager.GetAppSetting<int>(Key1);    
                }
                return this._field1.Value;
            }
        }

实例字段的后期初始化有没有更简单的方法?

4

1 回答 1

5

Lazy<T>正如建议的那样,是一个不错的选择。

我通常使用的是以下...

提供你_field*是一个nullable

在您的财产中,您可以...

return this.__field1 ?? (this.__field1 = this._configManager.GetAppSetting<int>(Key1));  

编辑:

给定评论讨论 - 为什么不只使用 a non static approachover Lazy<T>,例如

private readonly Lazy<int?> _field;
// init in ctor
_field = new Lazy<int?>(() => YourFieldInit(""));
// use in property
return _field.Value ?? 0;  

编辑2:

还有一个小测试来澄清 Lazy 行为:

public class DoLazy
{
    Lazy<int?> _field;
    public DoLazy()
    {
        // 'lazy' gets initialized - but `YourFieldInit` is not called yet.
        _field = new Lazy<int?>(() => YourFieldInit(""));
    }
    int Property
    {
        get
        {
            // `YourFieldInit` is called here, first time.
            return _field.Value ?? 0;
        }
    }
    int? YourFieldInit(string test)
    {   // breakpoint here
        return -1;
    }
    public static void Test()
    {
        var lazy = new DoLazy();
        int val1 = lazy.Property;
        var val = lazy.Property;
    }
}

在 - 中放置一个断点YourFieldInit以查看它何时被实际调用。从您的例如 Main
调用。DoLazy.Test()

于 2013-04-10T10:13:46.967 回答