使用一个枚举作为一个属性参数 [英] Using an Enum as an Attribute Argument
本文介绍了使用一个枚举作为一个属性参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我想使用的代码:
公共枚举天{星期六= 1,周日,周一,周二,周三,周四,周五};
[EnumHelper(typeof运算(天数))]
公众日星期几{搞定;组; }
EnumHelper如下:
[AttributeUsage(AttributeTargets.Property,的AllowMultiple = TRUE)]
公共类EnumHelper:属性
{
公共类型MyEnum {搞定;组; }
公共EnumHelper(ENUM类型)
{
MyEnum =枚举;
}
}
我得到EnumHelper(天),错误是在这一点上枚举名称无效。难道我做错了什么,或者能不办?
更多信息
< 。p>我试图通过枚举(天),并随机返回的值之一
没关系:我是过于复杂这一部分。
解决方案
在属性中的参数只能是常数。
如果你想通过你必须通过唯一的类型枚举类型:
[EnumHelper(typeof运算(天数)) ]
公众日星期几{搞定;组; }
[AttributeUsage(AttributeTargets.Property,的AllowMultiple = TRUE)]
公共类EnumHelper:属性
{
公共类型MyEnum;
公共EnumHelper(ENUM类型)
{
MyEnum =枚举;
}
}
Here is the code I would like to use:
public enum Days { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri };
[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }
EnumHelper looks like:
[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
public Type MyEnum { get; set; }
public EnumHelper(Type enum)
{
MyEnum = enum;
}
}
The error I get on EnumHelper(Days) is that "Enum Name not valid at this point". Am I doing something wrong, or can this not be done?
MORE INFO
I am trying to pass the Enum (Days), and randomly get back one of the values.
NEVERMIND: I was over-complicating this part.
解决方案
The parameters in Attributes can be only constants. If you want pass the enum type you must pass only the type:
[EnumHelper(typeof(Days))]
public Days DayOfWeek { get; set; }
[AttributeUsage(AttributeTargets.Property,AllowMultiple=true)]
public class EnumHelper : Attribute
{
public Type MyEnum;
public EnumHelper(Type enum)
{
MyEnum = enum;
}
}
这篇关于使用一个枚举作为一个属性参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文