如何命名枚举与属性

发布于 2024-10-06 20:32:51 字数 314 浏览 1 评论 0原文

在下面的 C# 代码中,我不喜欢枚举名称与属性名称相同。

public enum CollarType
{
    Classic,
    VNeck
}

public class Shirt
{
    public CollarType CollarType { get ... }
}

在过去,当更多人使用匈牙利语/其他奇怪的命名(例如 class CShirt)时,这种冲突不会发生。但今天我经常遇到它。

你如何处理这种情况?您是否只是接受许多事物具有相同名称的事实,还是您有更好的命名方案?

In the following contrived C# code, I don't like that an enum name is the same as the property name.

public enum CollarType
{
    Classic,
    VNeck
}

public class Shirt
{
    public CollarType CollarType { get ... }
}

In the old days when more people were using hungarian / other bizarre naming like class CShirt, this kind of conflict didn't happen. But today I run into it constantly.

How do you handle this situation? Do you just live with the fact that so many things have the same name, or do you have a better naming scheme?

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

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

发布评论

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

评论(3

似最初 2024-10-13 20:32:51

枚举名称与属性名称相同的唯一限制是您不能将枚举定义为具有属性的类的嵌套类型。

例如,这确实不起作用

public class Shirt
{
    public enum CollarType
    {
        Classic,
        VNeck
    }

    public CollarType CollarType { get ... }
}

但是,从积极的一面来看,它确实使代码更具可读性,恕我直言,因为它显然。显示枚举值和属性之间的关联:

myShirt.CollarType = CollarType.Classic;

The only limitation of having the enum name be the same as the property name is that you cannot define the enum as nested type of the class with the property.

E.g. this does not work:

public class Shirt
{
    public enum CollarType
    {
        Classic,
        VNeck
    }

    public CollarType CollarType { get ... }
}

However, on the positive side, it does make the code more readable IMHO because it clearly< shows the association between the enum value and the property:

myShirt.CollarType = CollarType.Classic;
若言繁花未落 2024-10-13 20:32:51

是的,拥有与其类型名称同名的属性是绝对正常的。

Yes, it's absolutely normal to have a property with the same name as it's type name.

冷弦 2024-10-13 20:32:51

BCL 中的约定只是运行它。除了嵌套枚举之外,它不会导致任何含糊之处。

The convention in the BCL is just to run with it. With the exception of nested enums, it doesn't cause any ambiguities.

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