且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该使用什么AttributeTarget为枚举成员?

更新时间:2023-12-01 09:13:34

据我所知,没有一个专门用于枚举常量。你可以得到很可能是场,这限制了使用一类或结构(其中枚举常量将被视为对属​​性的目的)的字段成员最接近的。

Far as I know, there isn't one specifically for enum constants. The closest you could get would probably be "Field", which limits the use to field members of a class or struct (which Enum constants are treated as for purposes of attributes).

编辑:带来的解释为什么从评论,枚举常量正是这样,因此他们的价值观和用法是的直接嵌入到IL 。因此枚举声明是真的不怎么从创建一个静态的类定义静态常量成员不同的:

bringing the explanation of "why" up from the comments, Enum constants are exactly that, and as such their values and usages are embedded directly into the IL. An enum declaration is therefore really not very different from creating a static class definition with static constant members:

public static class MyEnum
{
    public const int Value1 = 0;
    public const int Value2 = 1;
    public const int Value3 = 2;
    public const int Value4 = 3;        
}



...唯一的区别是它从System.Enum派生这是值类型,而不是被引用类(您不能创建一个静态的结构,也不是一个unconstructible之一)。

... the only difference being that it derives from System.Enum which is a value type instead of being a reference class (you can't create a static struct, nor an unconstructible one).