在C#词典中给键和值命名,以提高代码的可读性 [英] Give names to Key and Value in C# Dictionary to improve code readability

查看:95
本文介绍了在C#词典中给键和值命名,以提高代码的可读性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C# struct, we can know clearly the purpose of a variable by it's name. For example,

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

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

Then, i know b.title is a type of string and it's referring to title.

但是在C#词典中,我们只能指定类型

However in C# dictionary, we can only specify the type

Dictionary<string,string> d

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

How can i make the code more readable such that the key of the dictionary is type of string and it is referring to title, and the value is type of string and it is referring to author? That means, other people can easily know that d["J.R.R. Tolkien"] is a wrong use of the dictionary when reading the code.

编辑 @mike z建议使用变量名称 titleToAuthor 来提高可读性.但是我真正的问题是在代码中有嵌套的字典.例如.

EDIT @mike z suggested to use a variable name titleToAuthor to help readability. But my real issue is that in the code there are nested dictionary. E.g.

Dictionary<string, Dictionary<string, string>>, 
or even 3 levels   
Dictionary<string, Dictionary<string , Dictionary< string , string[] >>>. 

我们希望在不创建自己的类的情况下方便使用Dictionary,但同时我们需要某种方法来提高可读性

We want to keep to convenience of using Dictionary without creating our own class but at the same time we need some way to improve the readability

推荐答案

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

As suggested by @ScottDorman you could define a new Type TitleAuthorDictionary that derives from Dictionary<string, string>, like so:

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,如下所示:

You could then use the more readable Dictionary Collection, like this:

TitleAuthorDictionary dictionary = new TitleAuthorDictionary();
dictionary.Add("Title1", "Author1");
dictionary.Add(title: "Title2", author: "Author2");
dictionary["Title2"] = "Author3";

这篇关于在C#词典中给键和值命名,以提高代码的可读性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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