Mat*_*ias 21 .net c# attributes windows-runtime
在WinRT .NET应用程序(C#)中,我想获取在枚举值上定义的自定义属性.以下面的枚举为例:
public enum MyEnum
{
[Display(Name="Foo")]
EnumValue1,
[Display(Name="Bar")]
EnumValue2
}
Run Code Online (Sandbox Code Playgroud)
现在在"普通".NET中我知道我能够获得枚举值的自定义属性enumValue.GetType().GetMember(enumValue.ToString()).
不幸的是,在WinRT .NET中GetMember(),Type类上没有该方法.
有什么建议怎么搭这个?
================================================== ===
感谢下面的Marc,我找到了答案!以下代码用于从.NET 4.5 WinRT中的枚举值获取特定的自定义属性:
public static class EnumHelper
{
public static T GetAttribute<T>(this Enum enumValue)
where T : Attribute
{
return enumValue
.GetType()
.GetTypeInfo()
.GetDeclaredField(enumValue.ToString())
.GetCustomAttribute<T>();
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 14
您可能应该专门查看字段,而不是寻找成员.如果Type在WinRT中没有这个,那么添加using System.Reflection;并使用type.GetTypeInfo()并查看,因为各种反射方面被移动到type-info.