枚举和匹配属性的 C# 命名约定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/495051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 05:37:35  来源:igfitidea点击:

C# naming convention for enum and matching property

c#.netenumsnaming-conventions

提问by Serge Wautier

I often find myself implementing a class maintaining some kind of own status property as an enum: I have a Status enum and ONE Status property of Status type. How should I solve this name conflict?

我经常发现自己实现了一个类,该类维护某种自己的状态属性作为枚举:我有一个 Status 枚举和一个 Status 类型的 Status 属性。我应该如何解决这个名称冲突?

public class Car
{
  public enum Status
  {
    Off,
    Starting,
    Moving
  };

  Status status = Status.Off;

  public Status Status // <===== Won't compile =====
  {
    get { return status; }
    set { status = value; DoSomething(); }
  }
}

If the Status enum were common to different types, I'd put it outside the class and the problem would be solved. But Status applies to Car only hence it doesn't make sense to declare the enum outside the class.

如果 Status 枚举对于不同类型是通用的,我会将它放在类之外,问题就会得到解决。但是 Status 仅适用于 Car,因此在类之外声明枚举是没有意义的。

What naming convention do you use in this case?

在这种情况下,您使用什么命名约定?

NB: This question was partially debated in comments of an answer of this question. Since it wasn't the mainquestion, it didn't get much visibility.

注意:这个问题在回答这个问题的评论中被部分讨论过。由于这不是主要问题,因此没有得到太多关注。

EDIT: Filip Ekberg suggests an IMO excellent workaround for the specific case of 'Status'. Yet I'd be interesting to read about solutions where the name of the enum/property is different, as in Michael Prewecki's answer.

编辑:Filip Ekberg 为特定的“状态”情况建议了 IMO 出色的解决方法。然而,我会很有趣地阅读有关枚举/属性名称不同的解决方案,如 Michael Prewecki 的回答

EDIT2 (May 2010): My favorite solution is to pluralize the enum type name, as suggested by Chris S. According to MS guidelines, this should be used for flag enums only. But I've come to like it more and more. I now use it for regular enums as well.

EDIT2(2010 年 5 月):我最喜欢的解决方案是按照 Chris S 的建议将枚举类型名称复数化。根据 MS 指南,这应该仅用于标志枚举。但我越来越喜欢它。我现在也将它用于常规枚举。

采纳答案by Chris S

I'll add my 1 euro to the discussion but it's probably not adding anything new.

我会将我的 1 欧元添加到讨论中,但它可能不会添加任何新内容。

The obvious solution is to move Status out of being a nested Enum. Most .NET enums (except possibly some in Windows.Forms namespace) aren't nested and it makes it annoying to use for the developer consuming your API, having to prefix the classname.

显而易见的解决方案是将 Status 从嵌套的 Enum 中移出。大多数 .NET 枚举(可能除了 Windows.Forms 命名空间中的一些)不是嵌套的,这使得使用 API 的开发人员很烦人,不得不为类名添加前缀。

One thing that hasn't been mentionedis that flag enums according to MSDN guidelines should be pluralized nounswhich you probably already know (Status is a simple enum so singular nouns should be used).

没有提到的一件事是,根据 MSDN 指南的标志枚举应该您可能已经知道的复数名词(Status 是一个简单的枚举,因此应该使用单数名词)。

State (enum called States) is the vocative, "Status" is the nominative of a noun that the English like most of our language absorbed from Latin. Vocative is what you name a noun for its condition and nominative is the subject of the verb.

State(枚举称为States)是呼格,“Status”是名词的主格,英语像我们的大部分语言一样从拉丁语中吸收而来。主格是您根据其条件命名名词的名称,而主格是动词的主语。

So in other words when the car is moving, that's the verb - moving is its status. But the car doesn't go off, its engine does. Nor does it start, the engine does (you probably picked an example here so this might be irrelevant).

所以换句话说,当汽车移动时,这是动词-移动是它的状态。但是汽车没有熄火,而是发动机熄火了。它也不会启动,引擎会启动(您可能在这里选择了一个示例,因此这可能无关紧要)。

public class Car
{
  VehicleState _vehicleState= VehicleState.Stationary;

  public VehicleState VehicleState 
  {
    get { return _vehicleState; }
    set { _vehicleState = value; DoSomething(); }
  }
}

public enum VehicleState
{
    Stationary, Idle, Moving
}

State is such a generalised noun wouldn't it be better to describe what state it is referring to? Like I did above

状态是这样一个广义名词,描述它所指的状态不是更好吗?就像我上面做的那样

The type example also in my view doesn't refer to the reader type, but its database. I would prefer it if you were describing the reader's database product which isn't necessarily relevant to the type of reader (e.g. the type of reader might be forward only, cached and so on). So

在我看来,类型示例也不是指读取器类型,而是指其数据库。如果您描述的读者的数据库产品不一定与读者的类型相关(例如,读者的类型可能是仅转发的、缓存的等等),我会更喜欢它。所以

reader.Database = Databases.Oracle;

In reality this never happens as they're implemented as drivers and an inheritance chain instead of using enums which is why the line above doesn't look natural.

实际上,这永远不会发生,因为它们被实现为驱动程序和继承链,而不是使用枚举,这就是为什么上面的行看起来不自然。

回答by Kieron

I usually prefix the enums, e.g. CarStatus. I suppose it all depends on team you're working with (if they have any rules/ processes for that sort of thing) and the objects usage. Just my 2 cents (:

我通常为枚举添加前缀,例如 CarStatus。我想这一切都取决于您正在合作的团队(如果他们对此类事情有任何规则/流程)和对象使用情况。只是我的 2 美分 (:

回答by Filip Ekberg

The definition of "Off", "Starting" and "Moving" is what i would call a "State". And when you are implying that you are using a "State", it is your "Status". So!

“关闭”、“开始”和“移动”的定义就是我所说的“状态”。当您暗示您正在使用“状态”时,它就是您的“状态”。所以!

public class Car
{
  public enum State
  {
    Off,
    Starting,
    Moving
  };

  State state = State.Off;

  public State Status
  {
    get { return state ; }
    set { state= value; DoSomething(); }
  }
}

If we take another example from the one stated where you'd like to use the word "Type" such in this case:

如果我们从另一个例子中你想在这种情况下使用“类型”这个词:

public class DataReader
{
    public enum Type
    {
        Sql,
        Oracle,
        OleDb
    }

    public Type Type { get; set; } // <===== Won't compile =====

}

You really need to see that there is a difference between enums and enums, right? But when creating a framework or talking about architecture you need to focus on the simillarities, ok lets find them:

你真的需要看到枚举和枚举之间有区别,对吧?但是在创建框架或谈论架构时,您需要关注相似之处,好吧,让我们找到它们:

When something is set to a State, it's defined as the "things" Status

当某物被设置为一个状态时,它被定义为“事物”状态

Example: The Car's Status is in Running State, Stopped State, and so on.

示例:汽车的状态为运行状态、停止状态等。

What you want to acheive in the second example is somewhat this:

你想在第二个例子中实现的是:

myDataReader.Type = DataReader.Database.OleDb

You might think that this says against what i've been preaching about to others, that you need to follow a standard. But, you are following a standard! The Sql-case is a specific case aswell and therefore need a somewhat specific solution.

您可能认为这与我一直在向他人宣讲的内容背道而驰,您需要遵循一个标准。但是,您正在遵循标准!Sql-case 也是一个特定的案例,因此需要一个特定的解决方案。

However, the enum would be re-usable within your System.Dataspace, and that's what the patterns is all about.

但是,枚举可以在您的System.Data空间中重复使用,这就是模式的全部意义所在。

Another case to look at with the "Type" is "Animal" where Type defines the Species.

使用“类型”查看的另一种情况是“动物”,其中类型定义了物种。

public class Animal
    {
        public enum Type
        {
            Mammal,
            Reptile,
            JonSkeet
        }

        public Type Species{ get; set; }

    }

This is following a pattern, you don't specificly need to "know" the Object for this and you are not specifing "AnimalType" or "DataReaderType", you can re-use the enums in your namespace of choice.

这是遵循一种模式,您不需要专门为此“知道”对象,并且您没有指定“AnimalType”或“DataReaderType”,您可以在您选择的命名空间中重用枚举。

回答by TWith2Sugars

I'd change the name of the property to something like "CurrentStatus". Quick an easy :)

我会将该属性的名称更改为“CurrentStatus”之类的名称。快速简单:)

回答by Jon Limjap

I think the real problem here is that the enum Status is encapsulated within your class, such that Car.Statusis ambiguous to both the property Statusand the enum Status

我认为这里真正的问题是枚举状态被封装在你的类中,这样Car.Status对属性Status和枚举都是不明确的Status

Better yet, put your enum outside of the class:

更好的是,将您的枚举放在课堂之外:

public enum Status
{
    Off,
    Starting,
    Moving
}

public class Car
{
    public Status Status
    { ... }
}

UPDATE

更新

Due to the comments below, I'll explain my design above.

由于下面的评论,我将在上面解释我的设计。

I'm one who doesn't believe that enums or classes or any other object should reside insideanother class, unless it will be totally private within that class. Take the above example, for instance:

我不相信枚举或类或任何其他对象应该驻留另一个类中,除非它在该类中是完全私有的。以上面的例子为例:

public class Car
{
    public enum Status
    {...}
    ...
    public Status CarStatus { get; set;}
}

While some commenters would argue that Status doesn't have any meaning outside the scope of the class Car, the fact that you are setting a publicproperty means that there are other parts of the program that willuse that enum:

虽然一些评论者会争辩说 Status 在类 Car 的范围之外没有任何意义,但您设置公共属性的事实意味着程序的其他部分使用该枚举:

public Car myCar = new Car();
myCar.CarStatus = Car.Status.Off;

And thatto me is a code smell. If I'm going to look at that status outsideof Car, I might as well define it outsideas well.

对我来说是一个代码味道。如果我要去看看那个状态之外Car,我还不如把它定义之外也是如此。

As such, I will probably just rename it as:

因此,我可能会将其重命名为:

public enum CarStatus
{...}

public class Car
{
    ...
    public CarStatus Status { get; set; }
}

However, if that enum will be used within and only withinthe car class, then I'm fine with declaring the enum there.

但是,如果该枚举仅在汽车类中使用,那么我可以在那里声明枚举。

回答by Chris S

I know my suggestion goes against the .NET Naming conventions, but I personally prefix enums with 'E' and enum flags with 'F' (similar to how we prefix Interfaces with 'I'). I really do not understand why this is not the convention. Enums/Flags are a special case like Interfaces that will never change their type. Not only does it make it clear what it is, it's very easy to type in intellisense since the prefix will filter most other types/variables/etc, and you won't have these naming clashes.

我知道我的建议与 .NET 命名约定背道而驰,但我个人用“E”和枚举标志前缀“F”(类似于我们如何用“I”前缀接口)。我真的不明白为什么这不是约定。枚举/标志是一种特殊情况,如接口永远不会改变它们的类型。它不仅清楚地表明它是什么,而且很容易输入智能感知,因为前缀将过滤大多数其他类型/变量/等,并且您不会有这些命名冲突。

And that would also solve another problem where for examples in WPF they use static classes like enums (e.g. FontWeights) that have pre-defined instances of types but you would not know if you don't search for it. If they just prefixed them with 'E', all you would have to do is type on character to find these special static classes.

这也将解决另一个问题,对于 WPF 中的示例,它们使用静态类,如具有预定义类型实例的枚举(例如 FontWeights),但如果您不搜索它,您将不知道。如果他们只是用“E”作为前缀,您所要做的就是输入字符以找到这些特殊的静态类。

回答by Kristian Wedberg

I suggest adding "Option" to the type name (or Flag if it contains bit flags), i.e. type is Car.StatusOption and property is Car.Status.

我建议在类型名称中添加“Option”(或 Flag,如果它包含位标志),即类型是 Car.StatusOption,属性是 Car.Status。

Compared to pluralizing, this avoids naming collisions when creating collections of the enum type, where you would normally want to pluralize the collection property, not the enum type.

与复数化相比,这在创建枚举类型的集合时避免了命名冲突,在这种情况下,您通常希望对集合属性进行复数化,而不是枚举类型

回答by nathanchere

Haters of Hungarian notation and its variants be damned. I use a convention of suffixing enums with - wait for it - Enum. I consequently never have the problem you describe, waste time worrying about what to call them and the code is readable and self-descriptive to boot.

讨厌匈牙利符号及其变体的人该死。我使用后缀枚举的约定 - 等待它 - Enum。因此,我从来没有遇到过您描述的问题,浪费时间担心如何称呼它们,并且代码可读且可自我描述以启动。

public class Car
{
  public enum StatusEnum
  {
    Off,
    Starting,
    Moving
  };

  public StatusEnum Status { get; set; }

}