2016-04-12 22 views
2

在C++中,如果我希望在編譯時初始化一個對象,並且此後永遠不會更改,那麼我只需添加前綴const如何在C#中獲得C++的「const」等價物?

在C#,我寫

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

並且得到錯誤

字符串以外引用類型的常量字段只能 初始化空

然後我研究堆棧溢出的錯誤,提出的「解決方案」是使用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

'私人靜態只讀ReadOnlyCollection ' –

+0

您找到了答案,並錯過它重要的一點(它包含的提示)。學習很難。 – Sinatr

回答

9

您要使用的readonly修改

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

編輯

只注意到了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);