使用属性引用字典中的键值对的最佳方法

时间:2022-09-15 14:02:54

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.

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

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

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

7 个解决方案

#1


4  

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

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

#2


1  

I agree with @Glenn for a purely nit-picky point of view. The answer is whatever works for you. All this code takes place in 10 lines (if you include the omitted last curly brace). Nobody is going to get lost and the chance of mistyping is pretty slim (not impossible but very slim). On the other hand, if you used the key somewhere else, then DEFINATELY go with the constant.

我同意@Glenn的纯粹挑剔观点。答案是适合你的。所有这些代码都在10行中进行(如果包含省略的最后一个大括号)。没有人会迷路而且错误输入的机会相当渺茫(并非不可能,但非常渺茫)。另一方面,如果您在其他地方使用了密钥,那么请务必使用常量。

Personally, I would go off on you about your curly brace style. :) Just kidding! It really is a matter of style.

就个人而言,我会谈谈你的大括号风格。 :) 开玩笑!这真的是一种风格问题。

#3


0  

This isn't answering your question, but I don't think "DefaultValue" means what you think it means. It doesn't set a default value for your property.

这不是回答你的问题,但我不认为“DefaultValue”意味着你的意思。它没有为您的属性设置默认值。

See MSDN and this question for more details.

有关更多详细信息,请参阅MSDN和此问题。

#4


0  

A lot of people would probably argue that the second option is "correct", because any value used more than once should be refactored into a constant. I would most likely use the first option. You have already gotten close to the "Code Complete" solution by encapsulating the dictionary entry in a strong typed property. This reduces the chance of screwing up retrieving the wrong Dictionary entry in your implementation. There are only 2 places where you could mess up typing "myKey", in the getter and setter, and this would be very easy to spot.

很多人可能认为第二个选项是“正确的”,因为任何一次使用的值都应该重构为常量。我很可能会使用第一个选项。您已经通过将字典条目封装在强类型属性中来接近“代码完成”解决方案。这减少了在实现中修复错误的Dictionary条目的可能性。在getter和setter中,只有2个地方可以输入“myKey”,这很容易被发现。

The second option would just get too messy.

第二种选择会变得太乱。

#5


0  

When you only use a magic string in one context, like you do, I think it's alright.
But if you ever need to use the key in another part of the class, go const.

当你只在一个上下文中使用魔术字符串时,就像你一样,我认为没关系。但是如果你需要在类的另一部分使用密钥,那就去const吧。

#6


0  

You could match the property names up to the keys and use reflection to get the name for the lookup.

您可以将属性名称与键匹配,并使用反射来获取查找的名称。

public string FirstProperty {
get {
    return Dictionary[PropertyName()];
}
set {
    Dictionary[PropertyName()] = value;
}

private string PropertyName()
{
    return new StackFrame(1).GetMethod().Name.Substring(4);
}

This has the added benefit of making all your property implementation identical, so you could set them up in visual studio as code snippets if you want.

这样做的另一个好处是可以使所有属性实现完全相同,因此如果需要,可以将它们设置为visual studio中的代码片段。

#7


0  

@Joel you don't want to count on StackFrame. In-lining can ruin your day when you least expect it.

@Joel你不想指望StackFrame。内衬可能会在您最不期望的时候破坏您的一天。

But to the question: Either way doesn't really matter a whole lot.

但问题是:无论哪种方式并不重要。

#1


4  

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

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

#2


1  

I agree with @Glenn for a purely nit-picky point of view. The answer is whatever works for you. All this code takes place in 10 lines (if you include the omitted last curly brace). Nobody is going to get lost and the chance of mistyping is pretty slim (not impossible but very slim). On the other hand, if you used the key somewhere else, then DEFINATELY go with the constant.

我同意@Glenn的纯粹挑剔观点。答案是适合你的。所有这些代码都在10行中进行(如果包含省略的最后一个大括号)。没有人会迷路而且错误输入的机会相当渺茫(并非不可能,但非常渺茫)。另一方面,如果您在其他地方使用了密钥,那么请务必使用常量。

Personally, I would go off on you about your curly brace style. :) Just kidding! It really is a matter of style.

就个人而言,我会谈谈你的大括号风格。 :) 开玩笑!这真的是一种风格问题。

#3


0  

This isn't answering your question, but I don't think "DefaultValue" means what you think it means. It doesn't set a default value for your property.

这不是回答你的问题,但我不认为“DefaultValue”意味着你的意思。它没有为您的属性设置默认值。

See MSDN and this question for more details.

有关更多详细信息,请参阅MSDN和此问题。

#4


0  

A lot of people would probably argue that the second option is "correct", because any value used more than once should be refactored into a constant. I would most likely use the first option. You have already gotten close to the "Code Complete" solution by encapsulating the dictionary entry in a strong typed property. This reduces the chance of screwing up retrieving the wrong Dictionary entry in your implementation. There are only 2 places where you could mess up typing "myKey", in the getter and setter, and this would be very easy to spot.

很多人可能认为第二个选项是“正确的”,因为任何一次使用的值都应该重构为常量。我很可能会使用第一个选项。您已经通过将字典条目封装在强类型属性中来接近“代码完成”解决方案。这减少了在实现中修复错误的Dictionary条目的可能性。在getter和setter中,只有2个地方可以输入“myKey”,这很容易被发现。

The second option would just get too messy.

第二种选择会变得太乱。

#5


0  

When you only use a magic string in one context, like you do, I think it's alright.
But if you ever need to use the key in another part of the class, go const.

当你只在一个上下文中使用魔术字符串时,就像你一样,我认为没关系。但是如果你需要在类的另一部分使用密钥,那就去const吧。

#6


0  

You could match the property names up to the keys and use reflection to get the name for the lookup.

您可以将属性名称与键匹配,并使用反射来获取查找的名称。

public string FirstProperty {
get {
    return Dictionary[PropertyName()];
}
set {
    Dictionary[PropertyName()] = value;
}

private string PropertyName()
{
    return new StackFrame(1).GetMethod().Name.Substring(4);
}

This has the added benefit of making all your property implementation identical, so you could set them up in visual studio as code snippets if you want.

这样做的另一个好处是可以使所有属性实现完全相同,因此如果需要,可以将它们设置为visual studio中的代码片段。

#7


0  

@Joel you don't want to count on StackFrame. In-lining can ruin your day when you least expect it.

@Joel你不想指望StackFrame。内衬可能会在您最不期望的时候破坏您的一天。

But to the question: Either way doesn't really matter a whole lot.

但问题是:无论哪种方式并不重要。