2012-01-30 22 views
2

文字列を持つ静的ReadOnlyCollectionを作成したいとします。静的な読み取り専用の文字列のコレクションの割り当て

この式を何らかの方法で短くするか、よりエレガントにする方法はありますか?

public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>(
    new string[] { 
    "string1", 
    "string2", 
    "string3", 
    } 
); 

私はこれを何回も使用しますが、ファイルは異なります。

+2

あなたは '新しい文字列[] {...'で 'STRING'を省略することができませんでしたが、何か... – SWeko

答えて

8
public static readonly ReadOnlyCollection<string> ErrorList = new ReadOnlyCollection<string>(
    new [] { 
    "string1", 
    "string2", 
    "string3" 
    } 
); 
8

別のオプションは、コレクション初期化子でList<T>を使用することで、AsReadOnly方法:

public static readonly ReadOnlyCollection<string> ErrorList = new List<String> { 
    "string1", 
    "string2", 
    "string3", 
    }.AsReadOnly(); 
+1

しかし、それはよりエレガントですか? –

+1

@FrederikGheysels:個人的にどちらのアプローチにも満足しています。私は明示的に配列を作成し、それをラップすることよりもこれを好むと思うが、どちらも同じようにうまくいく。 –

2

私が考える最もコンパクトである:

using StringCol = ReadOnlyCollection<string>; 
... 
public static readonly StringCol ErrorList = new StringCol(
     new[] 
     { 
     "string1", 
     "string2", 
     "string3", 
     }); 

usingディレクティブはちょうどここにありますReadOnlyCollection<string>をたくさん使用している場合のコード量を減らすためです。そうでない場合、何も減らさないでしょう。

+2

Picky:それはusingステートメントではなく、usingステートメントです。しかし、私はそれが利用可能な最もコンパクトなフォームだとは思わない:) –

+1

@JonSkeet '使用'の間違いを指摘してくれてありがとう、編集;)そして実際にはあなたが右それはここでは最短ではない。 – ken2k

0

私は、この記事の大きな回答のいくつかを組み合わせることで別の可能性を考えました。

paramsとカスタムメソッドを作成します。

public static ReadOnlyCollection<String> CreateStringsReadOnlyCollection(params string[] st){ 

     return new ReadOnlyCollection<String>(st); 
    } 

をし、それが好きで使用して:

public readonly static ReadOnlyCollection<String> col = CreateStringsReadOnlyCollection("string1", "string2", "string3"); 
1

Array.AsReadOnly<T>new[]は配列の内容を推測することができます。

public static readonly ReadOnlyCollection<string> ErrorList = Array.AsReadOnly(
    new[] { 
    "string1", 
    "string2", 
    "string3", 
    } 
); 

場合あなたはインターフェイスで作業しても構わない、ReadOnlyCollection<T> implements several of themIList<T>含む:

文体
public static readonly IList<string> ErrorList = Array.AsReadOnly(
    new[] { 
    "string1", 
    "string2", 
    "string3", 
    } 
); 

、私は一つのブロックに対して複数のくぼみを避けることを好む:

public static readonly IList<string> ErrorList = Array.AsReadOnly(new[] { 
    "string1", 
    "string2", 
    "string3", 
}); 
関連する問題