C# 我需要一种优雅的方法从枚举中提取备用数据
我正在寻找一种从枚举中获取备用值的方法,并引用了这个答案 在这里,它使用一个description属性来指定一个值,然后使用一个方法来提取该值C# 我需要一种优雅的方法从枚举中提取备用数据,c#,enums,compact-framework,C#,Enums,Compact Framework,我正在寻找一种从枚举中获取备用值的方法,并引用了这个答案 在这里,它使用一个description属性来指定一个值,然后使用一个方法来提取该值 publicstaticstringdescriptionatr(此T源代码){ FieldInfo fi=source.GetType().GetField(source.ToString()); DescriptionAttribute[]属性=(DescriptionAttribute[])fi.GetCustomAttributes( type
publicstaticstringdescriptionatr(此T源代码){
FieldInfo fi=source.GetType().GetField(source.ToString());
DescriptionAttribute[]属性=(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),false);
如果(attributes!=null&&attributes.Length>0)返回属性[0]。说明;
else返回source.ToString();}
只是我不幸地陷入了.net 3.5 Compact Framework的黑暗时代,似乎无法访问System.ComponentModel.DescriptionAttribute
谁能给我一个提示,如何让这样的东西工作…我不确定这就是你想要的。我只是对原始代码做了一些更改:
static class MyClass
{
public static string DescriptionAttr<T>(this T source, Type attrType, string propertyName)
{
FieldInfo fi = source.GetType().GetField(source.ToString());
var attributes = fi.GetCustomAttributes(attrType, false);
if (attributes != null && attributes.Length > 0)
{
var propertyInfo = attributes[0].GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
var value = propertyInfo.GetValue(attributes[0], null);
return value as string;
}
}
else
return source.ToString();
return null;
}
}
public enum MyEnum
{
Name1 = 1,
[MyAttribute("Here is another")]
HereIsAnother = 2,
[MyAttribute("Last one")]
LastOne = 3
}
class MyAttribute : Attribute
{
public string Description { get; set; }
public MyAttribute(string desc)
{
Description = desc;
}
}
你可以很容易地实现你自己的自定义属性,这就是你在这里可能需要做的。事实上,这正是我想要的。非常感谢您花时间演示。属性[0]在那里并不优雅。你可能想改变这一点。请将问题标记为有效,我已重构这个问题的答案非常简单,但它启发了我如何应用自定义属性以及如何反映和挖掘信息。我想我应该让它静一静,看看其他人有什么想法
static class MyClass
{
public static string DescriptionAttr<T>(this T source, Type attrType, string propertyName)
{
FieldInfo fi = source.GetType().GetField(source.ToString());
var attributes = fi.GetCustomAttributes(attrType, false);
if (attributes != null && attributes.Length > 0)
{
var propertyInfo = attributes[0].GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
var value = propertyInfo.GetValue(attributes[0], null);
return value as string;
}
}
else
return source.ToString();
return null;
}
}
public enum MyEnum
{
Name1 = 1,
[MyAttribute("Here is another")]
HereIsAnother = 2,
[MyAttribute("Last one")]
LastOne = 3
}
class MyAttribute : Attribute
{
public string Description { get; set; }
public MyAttribute(string desc)
{
Description = desc;
}
}
var x = MyEnum.HereIsAnother.DescriptionAttr(typeof(MyAttribute), "Description");