我有一个包含 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;
}
}
实例字段的后期初始化有没有更简单的方法?