使用属性引用字典中的键值对的最佳方法[关闭](Best way to use a property to reference a Key

编程入门 行业动态 更新时间:2024-10-27 08:31:29
使用属性引用字典中的键值对的最佳方法[关闭](Best way to use a property to reference a Key-Value pair in a dictionary [closed])

这是一个相当微不足道的事情,但我很想听听人们对此的看法。

如果我有一个我可以通过属性访问的词典,那么您更喜欢这些格式的属性?

/// <summary> /// This class's FirstProperty property /// </summary> [DefaultValue("myValue")] public string FirstProperty { get { return Dictionary["myKey"]; } set { Dictionary["myKey"] = value; }

这可能是这种做法的典型方式。 它非常有效,易于理解等。唯一的缺点是使用更长或更复杂的密钥,可能会拼错它或仅更改一个实例或某些内容,从而引导我:

/// <summary> /// This class's SecondProperty property /// </summary> [DefaultValue("myValue")] private const string DICT_MYKEY = "myKey" public string SecondProperty { get { return Dictionary[DICT_MYKEY]; } set { Dictionary[DICT_MYKEY] = value; }

这稍微复杂一点,但似乎提供额外的安全性,并且更接近我所能想到的“代码完整”解决方案。 缺点是,当你的属性上面还有一个///块和一个[DefaultValue()]块时,它开始变得有点拥挤。

那么你更喜欢哪个,为什么? 有没有人有更好的想法?

This is a fairly trivial matter, but I'm curious to hear people's opinions on it.

If I have a Dictionary which I'm access through properties, which of these formats would you prefer for the property?

/// <summary> /// This class's FirstProperty property /// </summary> [DefaultValue("myValue")] public string FirstProperty { get { return Dictionary["myKey"]; } set { Dictionary["myKey"] = value; }

This is probably the typical way of doing it. It's fairly efficient, easy to understand, etc. The only disadvantage is with a longer or more complex key it would be possible to misspell it or change only one instance or something, leading me to this:

/// <summary> /// This class's SecondProperty property /// </summary> [DefaultValue("myValue")] private const string DICT_MYKEY = "myKey" public string SecondProperty { get { return Dictionary[DICT_MYKEY]; } set { Dictionary[DICT_MYKEY] = value; }

Which is marginally more complicated, but seems to offer additional safety, and is closer to what I would think of as the "Code Complete" solution. The downside is that when you also have a /// block and a [DefaultValue()] block above the property already, it starts getting a bit crowded up there.

So which do you like better, and why? Does anybody have any better ideas?

最满意答案

我非常喜欢第二个,因为在代码中避免使用魔术字符串/数字是一件好事。 IMO如果你需要多次引用代码中的数字或字符串文字,它应该是一个常量。 在大多数情况下,即使它只使用一次它应该是一个常数

I like the second one purely because any avoidance of magic strings/numbers in code is a good thing. IMO if you need to reference a number or string literal in code more than once, it should be a constant. In most cases even if it's only used once it should be in a constant

更多推荐

本文发布于:2023-08-07 08:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1463316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:键值   字典   属性   方法   Key

发布评论

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

>www.elefans.com

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