How can I get the equivalent of C++'s "const" in C#?

This question already has an answer here:

  • What is the difference between const and readonly? 31 answers

  • You want to use the readonly modifier

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

    EDIT

    Just noticed that the ReadOnlyCollection type doesnt allow an empty constructor or supplying of the list in the brackets. You must supply the list in the constructor.

    So really you can just write it as a normal list which is readonly.

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

    or if you really want to use the ReadOnlyCollection you need to supply the above normal list in the constructor.

    private readonly static ReadOnlyCollection<string> _ExtensionsOfInterest = new ReadOnlyCollection<string>(_ExtensionsOfInterestList);
    
    链接地址: http://www.djcxy.com/p/21220.html

    上一篇: 为什么C#有'只读'和'常量'?

    下一篇: 我怎样才能在C#中获得相当于C ++的“const”?