.NET Dictionary as a Property

后端 未结 8 503
-上瘾入骨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:23

    sample code:

    public class MyClass
    {
      public MyClass()
      {
        TheDictionary = new Dictionary();
      }
    
      // private setter so no-one can change the dictionary itself
      // so create it in the constructor
      public IDictionary TheDictionary { get; private set; }
    }
    

    sample usage:

    MyClass mc = new MyClass();
    
    mc.TheDictionary.Add(1, "one");
    mc.TheDictionary.Add(2, "two");
    mc.TheDictionary.Add(3, "three");
    
    Console.WriteLine(mc.TheDictionary[2]);
    

    EDIT

    When you use C# version 6 or later, you can also use this:

    public class MyClass
    {
      // you don't need a constructor for this feature
    
      // no (public) setter so no-one can change the dictionary itself
      // it is set when creating a new instance of MyClass
      public IDictionary TheDictionary { get; } = new Dictionary();
    }
    

提交回复
热议问题