2011-12-11 71 views
11

結合構造,我有以下代碼:我可以在C#

public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID) 
    { 
     this._modelState = modelStateDictionary; 
     this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID); 
     this._productRepository = StorageHelper.GetTable<Product>(dataSourceID); 
    } 

    public AccountService(string dataSourceID) 
    { 
     this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID); 
     this._productRepository = StorageHelper.GetTable<Product>(dataSourceID); 
    } 

有一些辦法,我可以簡化構造所以每個不必做StorageHelper電話?

我也需要指定這個。 ?

回答

22
public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID) 
    : this(dataSourceID) 
{ 
    this._modelState = modelStateDictionary; 

} 

這將首先調用你的其他構造函數。您也可以使用base(...來調用基礎構造函數。

this在這種情況下是隱含的。

6

是的,你有兩個選擇:

1)摘要常見的初始化邏輯成另一種方法,並呼籲從每個構造。如果你需要控制哪些項目被初始化(即,如果_modelState需要_accountRepository後進行初始化)的順序,你就需要這個方法:

public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID) 
{ 
    this._modelState = modelStateDictionary; 
    Initialize(dataSourceID); 
} 

public AccountService(string dataSourceID) 
{ 
    Initialize(dataSourceID); 
} 

private void Initialize(string dataSourceID) 
{ 
    this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID); 
    this._productRepository = StorageHelper.GetTable<Product>(dataSourceID); 
} 

2)級聯構造函數通過在結尾處增加this

public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID) : this(dataSourceID) 
{ 
    this._modelState = modelStateDictionary; 
} 

public AccountService(string dataSourceID) 
{ 
    this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID); 
    this._productRepository = StorageHelper.GetTable<Product>(dataSourceID); 
} 
+0

只是爲了確認。我可以刪除哪些「這個」這個詞? –

+0

不完全清楚你要問什麼,但如果你詢問'this._'代碼,你可以刪除所有這些代碼。例如,'this._accountRepository'也可以寫成'_accountRepository'。我所指的'this'與構造函數聲明位於同一行(滾動到右邊看它)。 –

+1

@RichardM:幾乎所有的人。除非你傳入一個具有相同名字的變量,否則''this.'幾乎總是可以在上下文中被推斷出來。有些人喜歡它,引用可讀性(更明確)。其他人也出於同樣的原因不喜歡它(冗餘信息)。 –