How to write a getter and setter for a Dictionary?

前端 未结 6 1692
暗喜
暗喜 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 10:07

    It is not possible to do it in a way that would involve only properties. You theoretically could write a setter, but for a getter, you would need to specify a key that you want to retrieve. That is impossible since properties do not accept parameters. Natural way to accomplish what you want would be to use methods:

    private Dictionary users = new Dictionary();
    
    public void Set(string key, string value)
    {
        if (users.ContainsKey(key))
        {
            users[key] = value;
        }
        else
        {
            users.Add(key, value);
        }
    }
    
    public string Get(string key)
    {
        string result = null;
    
        if (users.ContainsKey(key))
        {
            result = users[key];
        }
    
        return result;
    }
    

    Alternatively, as others have already said, you could use indexers, but I've always found them a little cumbersome. But I guess it's just a matter of personal preference.

    And just for the sake of completeness, this is how a setter could look like, although it's highly unusual and counter-intuitive to have such a property:

    public KeyValuePair Users
    {
        set
        {
            Set(value.Key, value.Value);
        }
    }
    

    Internally, it uses the Set method from my previous snippet.

提交回复
热议问题