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

发布于 2024-07-04 22:29:02 字数 888 浏览 5 评论 0原文

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

如果我有一个可以通过属性访问的字典,您更喜欢该属性中的哪种格式?

/// <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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

如果没结果 2024-07-11 22:29:03

我同意@Glenn 纯粹挑剔的观点。 答案是任何对你有用的东西。 所有这些代码共 10 行(如果包含省略的最后一个大括号)。 没有人会迷路,而且输入错误的可能性非常小(不是不可能,但非常小)。 另一方面,如果您在其他地方使用了该密钥,那么一定要使用该常量。

就我个人而言,我会因为你的大括号风格而对你大发雷霆。 :) 只是在开玩笑! 这确实是一个风格问题。

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.

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

柠檬色的秋千 2024-07-11 22:29:03

我喜欢第二个纯粹是因为在代码中避免使用魔术字符串/数字是一件好事。 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

几度春秋 2024-07-11 22:29:03

@Joel你不想指望StackFrame。 内联可能会在您最意想不到的时候毁掉您的一天。

但对于问题:无论哪种方式都并不重要。

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

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

唠甜嗑 2024-07-11 22:29:03

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

请参阅 MSDN此问题了解更多详细信息。

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.

See MSDN and this question for more details.

梦冥 2024-07-11 22:29:03

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

第二种选择会变得太混乱。

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.

The second option would just get too messy.

你的往事 2024-07-11 22:29:03

当你只在一种情况下使用魔法字符串时,就像你所做的那样,我认为这是可以的。
但如果您需要在类的其他部分使用该键,请使用const

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.

妄司 2024-07-11 22:29:03

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

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

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文