在C#结构中,我们可以通过其名称清楚地了解变量的用途。例如,

public struct Book
{
    public string title;
    public string author;
}

然后,我知道b.title是字符串的一种,它指的是title。

但是在C#字典中,我们只能指定类型
Dictionary<string,string> d

如何使代码更具可读性,以使字典的键是字符串的类型,并且它是指标题,而值是字符串类型,并且是的作者?这意味着,其他人可以很容易地知道d [“J.R.R。Tolkien”]在阅读代码时是对词典的错误使用。

编辑
@mike z建议使用变量名 titleToAuthor 来提高可读性。但是我真正的问题是在代码中有嵌套的字典。例如。
Dictionary<string, Dictionary<string, string>>,
or even 3 levels
Dictionary<string, Dictionary<string , Dictionary< string , string[] >>>.

我们希望在不创建自己的类的情况下保持使用Dictionary的便利,但与此同时,我们需要一些方法来提高可读性

最佳答案

正如@ScottDorman所建议的,您可以定义一个新的TitleAuthorDictionary类型,它是从Dictionary<string, string>派生的,如下所示:

public class TitleAuthorDictionary : Dictionary<string, string>
{
    public new void Add(string title, string author)
    {
        base.Add(title, author);
    }

    public new string this[string title]
    {
        get { return base[title]; }
        set { base[title] = value; }
    }
}

然后,您可以使用更具可读性的Dictionary Collection,如下所示:
TitleAuthorDictionary dictionary = new TitleAuthorDictionary();
dictionary.Add("Title1", "Author1");
dictionary.Add(title: "Title2", author: "Author2");
dictionary["Title2"] = "Author3";

关于c# - 在C#词典中为键和值命名,以提高代码的可读性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30496657/

10-10 22:30