.NET Dictionary as a Property

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

    You could also look into indexers. (official MSDN documentation here)

    class MyClass
    {
        private Dictionary data = new Dictionary();
    
        public MyClass()
        {
            data.Add("Turing, Alan", "Alan Mathison Turing, OBE, FRS (pronounced /ˈtjʊ(ə)rɪŋ/) (23 June, 1912 – 7 June, 1954) was a British mathematician, logician, cryptanalyst and computer scientist.")
            //Courtesy of [Wikipedia][3]. Used without permission
        }
    
        public string this [string index]
        {
            get
            {
                return data[index];
            }
        }
    }
    

    Then, once you have populated the dictionary internally, you can access it's information by going

    MyClass myExample = new MyClass();
    
    string turingBio = myExample["Turing, Alan"];
    

    EDIT

    Obviously, this has to be used carefully, because MyClass is NOT a dictionary, and you cannot use any dictionary methods on it unless you implement them for the wrapper class. But indexers are a great tool in certain situations.

提交回复
热议问题