Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 我应该为枚举成员使用什么AttributeTarget?_C#_.net_Enums_Custom Attributes - Fatal编程技术网

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

C# 我应该为枚举成员使用什么AttributeTarget?,c#,.net,enums,custom-attributes,C#,.net,Enums,Custom Attributes,我想对enum成员使用我的isgpattribute,如下所示: public enum EffectType { [IsGPUBased(true)] PixelShader, [IsGPUBased(false)] Blur } 但是编译器不允许我使用: [AttributeUsage (AttributeTargets.Enum, AllowMultiple = false)] 什么是正确的AttributeTarget值来限制对枚举成员的使用?据我所

我想对enum成员使用我的
isgpattribute
,如下所示:

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

    [IsGPUBased(false)]
    Blur
}
但是编译器不允许我使用:

[AttributeUsage (AttributeTargets.Enum, AllowMultiple = false)]

什么是正确的
AttributeTarget
值来限制对枚举成员的使用?

据我所知,没有专门针对枚举常量的值。最接近的可能是“Field”,它将使用限制为类或结构的字段成员(枚举常量被视为属性)

编辑:从注释中引出“为什么”的解释,枚举常量正是如此,因此它们的值和用法也是如此。因此,枚举声明与使用静态常量成员创建静态类定义没有太大区别:

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派生的,System.Enum是一种值类型,而不是一个引用类(您不能创建静态结构,也不能创建不可构造的结构)。

没有办法指定属性只能在Enum成员上使用。老实说,如果要有这样的多个属性,最好创建自己的
Effect
(或
EffectType
)类并将其作为普通属性实现

比如说,

public class EffectType
{
    public bool IsGpuBased { get; private set; }

    private EffectType(bool isGpuBased)
    {
        IsGpuBased = isGpuBased;
    }

    public static readonly EffectType PixelShader = new EffectType(true);
    public static readonly EffectType Blur = new EffectType(false);
}

采用这种方法将使您的代码更易于阅读,并且与元数据提取相比性能更好。

AttributeTargets.Field允许您对枚举值使用属性

[AttributeUsage(AttributeTargets.Field)]

谢谢,这很有效。你知道为什么MS没有为枚举常量提供一个吗?因为在编译级别上,枚举常量和普通成员字段之间没有太大区别;您必须检查包含的类型并确定它派生自Enum。此外,对于只能应用于枚举常量的属性,实际上没有太多的调用。我唯一应用于枚举常量的是DescriptionAttribute,来自System.ComponentModel,它可以应用于任何其他对象。谢谢,我也只对枚举常量使用了DescriptionAttribute,这是我在实际代码中使用的类似属性。你说没有太大区别,但是
enum
s作为一等公民的最大区别在于,他们为您提供了一种强类型的处理方式。在您的情况下,如果(MyEnum.Value1==235)或
inti=MyEnum.Value1,我可以这样做
;i=SomeOtherEnum.Value1
等。。我知道这篇文章确实很老了,但我现在的情况是根据条目值随机选择枚举值,使某些选项更容易出现,并排除无法随机的选项,
public enum Test{[DisallowRandom]None[entry(4)]Test1[entry(2)]Test2,[Entry(1)]Test3}
谢谢,实际的代码不是这样的,只是想为这个问题提供一个简化的假设示例。@Joan:我想它仍然支持我的建议。没关系,我只是说我发布的代码是虚构的,因为我只想知道属性对枚举常量的限制。@Joan:关于这个问题,我支持@KeithS的评论,因为它可能不存在,因为没有足够的需求。我仍然认为,与使用属性相比,自定义类型是更好的选择;)不完美,但比“全部”更具约束性,谢谢。
[AttributeUsage(AttributeTargets.Field)]