如何写一个解释一个getter和setter? [英] How to write a getter and setter for a Dictionary?

查看:150
本文介绍了如何写一个解释一个getter和setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你是如何定义的复杂数据类型的一个getter和setter如字典

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

public Dictionary<string, string> Users
{
    get
    {
        return m_Users;
    }

    set
    {
        m_Users = value;
    }
}

这返回整个字典?你可以写二传手来看看,看看,如果一个特定的键值对存在,然后如果它没有,添加它。否则更新当前的键值对?对于GET,可以返回一个特定的键值对,而不是整个字典的?

This returns the entire dictionary? Can you write the setter to look and see if a specific key-value pair exists and then if it doesn't, add it. Else update the current key value pair? For the get, can you return a specific key-value pair instead of the whole dictionary?

推荐答案

这是不可能做到它在将仅涉及属性的方法。您的理论上的可以写一个二传手,但对于一个getter,你就需要指定要检索的关键。既然属性不接受参数是不可能的。自然的方式来完成你想要的是使用方法:

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<string, string> users = new Dictionary<string, string>();

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<string, string> Users
{
    set
    {
        Set(value.Key, value.Value);
    }
}



在内部,它使用了我以前的片段设置方法。

这篇关于如何写一个解释一个getter和setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆