Advertisement
atsukanrock

What is the best type for collection property?

Apr 9th, 2012
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.17 KB | None | 0 0
  1. // メソッドの戻り値についても同じ悩みがあるにはある。
  2. // ただメソッドの戻り値の場合は、そもそも使い回すことが少ないし、使い回す場合でも
  3. // クライアントが十分コントロール可能(適切なタイミングで ToArray() 呼ぶとか)
  4. // なことが多いので、いつでも IEnumerable<T> でいいんじゃね感が割とある。
  5.  
  6. public class Parent1
  7. {
  8.     // クライアントから見て、列挙が何度も走ってしまう懸念がないのが良い。
  9.     // また、コレクションが変更されるのを想定してない感が割と出ている。
  10.     public Child[] Children { get; set; }
  11. }
  12.  
  13. public class Parent2
  14. {
  15.     // クライアントからすると、列挙が何度も走ってしまう懸念があり、良くない。
  16.     // それを避けたいクライアントは ToArray() などしてから使うかもしれないが、
  17.     // Parent1 のインスタンスを複数箇所で使い回す場合には避けようがない。
  18.     // コレクションが変更されるのを想定してない感は割と出ている。
  19.     public IEnumerable<Child> Children { get; set; }
  20. }
  21.  
  22. public class Parent3
  23. {
  24.     private readonly IList<Child> _children = new List<Child>();
  25.  
  26.     // クライアントからすると、null チェック不要なのが嬉しい。
  27.     // しかしコレクションが変更されるのを想定している感が満載なので、
  28.     // 例えば何かの検索メソッドの戻り値でには不適切に思える。
  29.     // 逆に変更されるのを想定しているところではこれが良さ気。
  30.     public IList<Child> Children
  31.     {
  32.         get { return _children; }
  33.     }
  34. }
  35.  
  36. public class Parent4
  37. {
  38.     // コレクションが変更を想定してないことを最も主張するのはこれ。
  39.     // しかし ReadOnlyCollection<T> なんて、BCL でほとんど見かけないけど使って良いのか。
  40.     // Immutable な型を実装するためにはかなり使える型だが、普段の Entity クラスの
  41.     // 開発なんかではまず不要。
  42.     public ReadOnlyCollection<Child> Children { get; set; }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement