是否可以向c#枚举对象添加自定义属性? [英] Is it possible to add custom properties to c# enum object?
问题描述
使用c#是否有可能用于关联每个枚举项的属性?
Using c# Is it possible using to associate properties for each enum items?
我使用了描述属性可以为枚举添加英语描述 code>项目。
I have used the Description Attribute to add English description to an enum
item.
要在每个项目中添加英文说明,我已经完成了以下操作
To add English description to each item I have done the following
public enum MyEnum
{
[Description("My First Item")]
First,
[Description("My Second Item")]
Second,
[Description("My Third Item")]
Third
}
然后我在枚举
中添加了一个扩展方法,称为 GetDescription()
,我可以这样获取描述
Then I added an extension method to my enum
called GetDescription()
which allows me to get the description like so
public static string GetDescription(this Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
{
return attr.Description;
}
}
}
return name;
}
但是,如果我能够分配课程,这将对我有很大帮助或构造一个新对象。
However, it will help me a lot if I am able to assign a class or construct a new object.
是否可以/如何执行以下操作?
Is it possible/How can I do something like the follow?
public enum MyEnum
{
[Description("My First Item"), new { IsFirst = true, UnitType = 1}]
First
}
或使用课程
public enum MyEnum
{
[Description("My First Item"), new MyCustomClass(true, 1)]
First
}
推荐答案
您可以使用自定义属性装饰元素。那些几乎可以包含您想要的任何内容。
You can decorate elements with custom Attributes. Those can contain nearly anything you want.
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class DescriptorAttribute : Attribute
{
public bool IsFirst { get; }
public int UnitType { get; }
public DescriptorAttribute(bool isFirst, int unitType)
{
IsFirst = isFirst;
UnitType = unitType;
}
}
您将使用以下方式:
public enum Test
{
[Descriptor(isFirst: true, unitType: 2)]
Element
}
您已经拥有读取问题中此属性的代码。
you already have the code to read this attribute in your question.
这篇关于是否可以向c#枚举对象添加自定义属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!