.NET Dictionary as a Property

后端 未结 8 491
-上瘾入骨i
-上瘾入骨i 2021-02-02 08:30

Can someone point me out to some C# code examples or provide some code, where a Dictionary has been used as a property for a Class.

The examples I have seen so far don\'

8条回答
  •  粉色の甜心
    2021-02-02 09:11

    In order to ensure the encapsulation is correct and the dictionary cannot be updated outside the class using Add or the form ExampleDictionary[1]= "test", use IReadOnlyDictionary.

    public class Example
    {
        private Dictionary exampleDictionary;
    
        public Example() 
        { 
            exampleDictionary = new Dictionary(); 
        }
    
        public IReadOnlyDictionary ExampleDictionary
        {
            get { return (IReadOnlyDictionary)exampleDictionary; }
        }
    }
    

    The following code will not work, which is not the case if IDictionary is used:

    var example = new Example();
    example.ExampleDictionary[1] = test;
    

提交回复
热议问题