2011-12-11 8 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を意味します。別の方法に

1)抽象共通初期化ロジックと各コンストラクタからそれを呼び出す:

6

はい、あなたは選択肢のカップルを持っています。あなたは(_modelStateがそれの後に初期化する_accountRepositoryを必要とする場合IE)の項目が初期化される順序を制御するために必要な場合は、この方法が必要になります

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

@リチャードM:まあまあです。同じ名前の変数を渡している場合を除いて、 'this.'はコンテキスト内でほぼ常に推論できます。読みやすさ(より明示的)を挙げて、好きな人もいます。他の人は同じ理由(冗長な情報)のためにそれを嫌う。 –