在C#词典中给键和值命名,以提高代码的可读性

编程入门 行业动态 更新时间:2024-10-27 22:23:45
本文介绍了在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#词典中给键和值命名,以提高代码的可读性

本文发布于:2023-11-06 01:53:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562424.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可读性   词典   代码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!