创建从 ENUM 到模型的列表
我得到了以下模型代码:
public enum EnumTest
{
[Description ("Enum Text 1")]
Value_1 = 1,
[Description ("Enum Text 2")]
Value_2 = 2,
}
public List<Fields> listFields = new List<Fields>();
public class Fields
{
public int Code { get; set;}
public string Description { get; set;}
}
我得到了一个枚举,我想用枚举值填充我的变量代码,并用相同的枚举描述填充变量描述。我查找了很长时间,但未能使用枚举值/描述将“ListFields”初始化到其构造函数中。
我已经获得了枚举和获取其描述的方法..我发现它很有用,所以我将其留在这里,也许它对某人有用..
public static string GetDescription(this Enum value)
{
return (from m in value.GetType().GetMember(value.ToString())
let attr =(DescriptionAttribute)m.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault()
select attr == null ? value.ToString() : attr.Description).FirstOrDefault();
}
要使用它,您只需要执行以下操作:
String xx = Enum.EnumName.GetDescription();
I got the following model piece of code:
public enum EnumTest
{
[Description ("Enum Text 1")]
Value_1 = 1,
[Description ("Enum Text 2")]
Value_2 = 2,
}
public List<Fields> listFields = new List<Fields>();
public class Fields
{
public int Code { get; set;}
public string Description { get; set;}
}
I got an Enum and I would like to fill my variable CODE with enum value and the variable Description with the same enum description. I looked up a long time and failed to initialize my "ListFields" into its constructor with the enum VALUE/DESCRIPTION.
I already got the enum and the method to get its description.. I found it usefull, so I'll leave it here, maybe it can be useful for someone..
public static string GetDescription(this Enum value)
{
return (from m in value.GetType().GetMember(value.ToString())
let attr =(DescriptionAttribute)m.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault()
select attr == null ? value.ToString() : attr.Description).FirstOrDefault();
}
To use this you just need to do something like this:
String xx = Enum.EnumName.GetDescription();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你必须使用反射。
使用它非常简单:
在我的实现中,当找不到描述属性时,将使用字段名称。
我们还必须说,反射可能很慢,并且如果您经常需要的话,在需要时重建整个数组是浪费时间。
您可以将数组存储在某个地方,这样您就可以只计算一次并将其缓存起来。
当然,正如我所说,只有当您经常需要这个只读列表时,这才有意义。
You have to use reflection.
To use it is quite simple:
In my implementation when a descriptionattribute is not found, field name is used.
We must also say that reflection can be slow and rebuilding the entire array when you need it is a waste of time, if you need it often.
You can store the array somewhere so you can compute it only once and keep it cached.
This of course and as I said, makes sense only if you need this readonly list very often.