2010-12-16 16 views
4

2つの初期化のどちらが良いですか?コンストラクタの内部または外部のメンバ初期化

public class ServiceClass 
{ 
    private DataManager dataManager = new DataManager(); 
    private Dictionary<string, string> stringDictionary = new Dictionary<string, string>(); 
    private Dictionary<string, DateTime> timeDictionary = new Dictionary<string, DateTime>(); 
    public ServiceClass() 
    { 
     //other object creation code 
    } 
} 

OR

public class ServiceClass 
{ 
    private DataManager dataManager; 
    private Dictionary<string, string> stringDictionary; 
    private Dictionary<string, DateTime> timeDictionary; 
    public ServiceClass() 
    { 
     dataManager = new DataManager(); 
     stringDictionary = new Dictionary<string, string>(); 
     timeDictionary = new Dictionary<string, DateTime>(); 
     //other object creation code 
    } 
} 
+0

[ベストプラクティス:コンストラクタまたは宣言でクラスフィールドを初期化するかどうかの可能な複製?](http://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at) -宣言) – Gishu

答えて

2

あなたは明示的なコンストラクタで他のコード(「他のオブジェクトの作成コード」)を持っているので、私はそこにすべての初期化を入れ好むだろう。

4

コンストラクタを使用することをお勧めします。

これは、残念ながら発見されたのは、シリアライザ(この場合はデータコントラクトシリアライザ)を介して再構築されたオブジェクトに、フィールドイニシャライザが呼び出されなかったためです。

さらに、すべての初期化ロジックが、コード全体に潜在的に散在するのではなく、グループ化されていることが保証されています(フィールド変数を定義したい場合)。

関連する問題