How to write a getter and setter for a Dictionary?

前端 未结 6 1694
暗喜
暗喜 2020-12-17 09:09

How do you define a getter and setter for complex data types such as a dictionary?

public Dictionary Users
{
    get
    {
        retu         


        
6条回答
  •  悲&欢浪女
    2020-12-17 09:48

    Use an indexer property (MSDN):

    public class YourClass
    {
        private readonly IDictionary _yourDictionary = new Dictionary();
    
        public string this[string key]
        {
            // returns value if exists
            get { return _yourDictionary[key]; }
    
            // updates if exists, adds if doesn't exist
            set { _yourDictionary[key] = value; }
        }
    }
    

    Then use like:

    var test = new YourClass();
    test["Item1"] = "Value1";
    

提交回复
热议问题