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

Joa*_*nge 41 .net c# enums custom-attributes

我想用我IsGPUBasedAttribute的enum成员这样:

public enum EffectType
{
    [IsGPUBased(true)]
    PixelShader,

    [IsGPUBased(false)]
    Blur
}
Run Code Online (Sandbox Code Playgroud)

但编译器不允许我使用:

[AttributeUsage (AttributeTargets.Enum, AllowMultiple = false)]
Run Code Online (Sandbox Code Playgroud)

AttributeTarget限制enum成员使用的正确价值是什么?

Kei*_*thS 58

据我所知,没有一个专门用于枚举常量.你可能得到的最接近的可能是"Field",它限制了对类或结构的字段成员的使用(Enum常量被视为属性的目的).

编辑:从注释中引入"为什么"的解释,Enum常量就是这样,因此它们的值和用法直接嵌入到IL中.因此,枚举声明与使用静态常量成员创建静态类定义实际上没有什么不同:

public static class MyEnum
{
    public const int Value1 = 0;
    public const int Value2 = 1;
    public const int Value3 = 2;
    public const int Value4 = 3;        
}
Run Code Online (Sandbox Code Playgroud)

...唯一的区别是它派生自System.Enum,它是一个值类型而不是一个引用类(你不能创建一个静态结构,也不能创建一个不可构造的结构).


Krz*_*tof 14

AttributeTarget.Field允许您使用枚举值的属性.