2016-04-12 4 views
2

C++では、オブジェクトをコンパイル時に初期化してから変更しない場合は、接頭辞constを追加するだけです。C#で "const"と同等のものを得るにはどうしたらいいですか?

C#では、私は

// file extensions of interest 
    private const List<string> _ExtensionsOfInterest = new List<string>() 
    { 
     ".doc", ".docx", ".pdf", ".png", ".jpg" 
    }; 

を作成し、文字列以外のレファレンスタイプのCONSTフィールドのみ がNULL

で初期化することができるエラーを

を得ますスタックオーバーフローに関するエラーを調べ、提案された "解決策"はReadOnlyCollection<T>を使用することです。 A const field of a reference type other than string can only be initialized with null Error

しかし

// file extensions of interest 
    private static ReadOnlyCollection<string> _ExtensionsOfInterest = new ReadOnlyCollection<string>() 
    { 
     ".doc", ".docx", ".pdf", ".png", ".jpg" 
    }; 

はまだを再割り当てすることができますので、それは本当に、私が欲しいの挙動を与えるものではありません。

私は何をしようとしていますか?

(これは、C#は私が欲しいものを除き、すべての言語機能imgaginableを持っているか驚くべきことだ)

+7

'' –

+0

プライベート静的読み取り専用ReadOnlyCollectionあなたは答えを発見し、それの重要な点を(それがヒントが含まれています)欠場します。学習は難しい。 – Sinatr

答えて

9

あなたは

private readonly static ReadOnlyCollection<string> _ExtensionsOfInterest = new ReadOnlyCollection<string>() 
{ 
    ".doc", ".docx", ".pdf", ".png", ".jpg" 
}; 

readonly修飾子を使用したいEDIT

ちょうどことに気づきましたReadOnlyCollection型では、空のコンストラクタまたは括弧内のリストの指定ができません。コンストラクタでリストを指定する必要があります。

本当にあなたは読んでいる普通のリストとしてそれを書くことができます。

private readonly static List<string> _ExtensionsOfInterestList = new List<string>() 
{ 
    ".doc", ".docx", ".pdf", ".png", ".jpg" 
}; 

またはあなたが本当にあなたは、コンストラクタで上記の通常のリストを提供する必要がありReadOnlyCollectionを使用したい場合。

private readonly static ReadOnlyCollection<string> _ExtensionsOfInterest = new ReadOnlyCollection<string>(_ExtensionsOfInterestList); 
関連する問題