最好的方法使用属性引用一个键值对的字典 [英] Best way to use a property to reference a Key-Value pair in a dictionary

查看:104
本文介绍了最好的方法使用属性引用一个键值对的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是个极其普通的事情,但我很好奇地听到它的人的意见。

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

如果我有一个意思,我是通过属性的访问,其中这些格式将你preFER的财产?

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;
    }

这是稍微复杂一些,但似乎提供了额外的安全性,是更接近我会认为是code完成的解决方案。不利的一面是,当你也有一个///块和[默认值()]块属性上面已经,它开始变得有点挤在那里。

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?

推荐答案

我喜欢第二个,纯粹是因为任何避税魔术字符串/数字在code是一件好事。 IMO如果您需要引用一个数字或字符串在code不止一次,它应该是一个常数。在即使它仅使用一次应该是在一个恒定的大多数情况下,

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

这篇关于最好的方法使用属性引用一个键值对的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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