![](/img/trans.png)
[英]How to get a custom attribute on enum by passing in the enum value and attribute type?
[英]How to get an enum value with either one of two attribute values
编辑:我更新了帖子以使用Guid
而不是int
。 感谢下面那些指出使用int
没有任何作用的人,因为枚举的基本类型是int
。
我有一个枚举,假设它是
public enum AnimalType
{
[Animal("00000000000000000000000000000001")]
Bear = 0,
[Animal("00000000000000000000000000000002")]
Cat = 1,
[Animal("00000000000000000000000000000003")]
Dog = 2
}
此枚举使用 Animal 属性,定义为:
public class AnimalAttribute : Attribute
{
public AnimalAttribute(Guid id)
{
this.AnimalId = id;
}
public AnimalAttribute(string id)
{
this.AnimalId = new Guid(id);
}
public Guid AnimalId { get; private set; }
// Some more properties
}
如您所见, AnimalAttribute
有两个构造AnimalAttribute
,允许将 id 作为string
或Guid
接受。 AnimalType
枚举使用string
构造函数。
所以到目前为止,只能通过知道 id 来访问枚举值。 假设我不知道与特定枚举值对应的 id,我还可以使用与每个枚举值相对应的一些名称/描述(可能只是 Bear 等的“Bear”)来访问枚举值。 我的问题是,如何设置它以便AnimalAttribute
可以接受 id(以及作为字符串或 Guid)或与枚举值对应的名称/描述? 我想为AnimalAttribute
制作另一个构造函数, AnimalAttribute
所示:
public AnimalAttribute(string name)
{
this.AnimalName = name; // assume there is an AnimalName property.
}
然后我可以为每个枚举值添加另一个属性,如下所示:
[Animal("00000000000000000000000000000001")]
[Animal("Bear")]
Bear = 0,
所以我可以提供任何一个值,我将能够获得枚举值。 问题是我不能让AnimalAttribute
的构造AnimalAttribute
接受string name
因为已经有另一个构造函数接受string id
。 如果我不能这样做,那么我想我可以使用可选参数制作构造函数。 有没有简单的方法来设置它?
不确定你的目标是什么,但你可能把它复杂化了。 使用具有int值的枚举然后定义具有不同int值的属性是没有意义的。
看看使用 DescriptionAttribute 代替。 它是内置的,可以满足您的需求。
查看获取枚举值的属性
如果我误解了你的场景的一些细节,请原谅我,但如果 Animal 属性的 AnimalId 属性总是等于 Enum 元素的 int 值,那么 Animal 属性不是不必要的吗? 你不能只做以下事情:
枚举:
public enum AnimalType
{
Bear = 0,
Cat = 1,
Dog = 2
}
要获得 int 值,只需转换枚举:
int animalVal = (int)AnimalType.Bear;
要按值获取动物名称:
string animalName = Enum.GetName(typeof(AnimalType), 0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.