0
我有一個5-6字段的類,應該在構造函數運行後初始化一次。在C#中,遲到初始化實例字段最簡單的方法是什麼?
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);
}
但我不喜歡在構造函數中只是簡單的任務除了寫邏輯。
從那時起,我無法使用那裏的_configManager例如我不能使用內聯初始化FIELD1例如:
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;
}
}
是否有實例字段的初始化後期任何簡單的方法?
+1,好方法 – 2013-04-10 10:30:55
@CuongLe爲什麼要刪除你的答案? – NSGaga 2013-04-10 10:31:28
這是不正確的 – 2013-04-10 10:32:01