获取枚举值的自定义属性自定义、属性

2023-09-02 12:02:45 作者:spark 火花、

在一个WinRT的.NET应用程序(C#)我想要得到的自定义属性,即是在一个枚举值定义。看看下面的枚举,例如:

 公开枚举MyEnum
{
    [显示(名称=富)
    EnumValue1,

    [显示(NAME =酒吧)
    EnumValue2
}
 

现在在正常。NET我知道我能得到一个枚举值的自定义属性与 enumValue.GetType()。GetMember(enumValue.ToString())

不幸的是,在WinRT的.NET中的 GetMember()方法不适用于Type类。 任何建议如何去用呢?

=============================================== ==

感谢马克下面,我发现在答案! 下面code工程,以从.NET 4.5的WinRT枚举值获取特定的自定义属性:

 公共静态类EnumHelper
{
    公共静态牛逼的getAttribute< T>(枚举enumValue)
        其中T:属性
    {
        返回enumValue
            .GetType()
            .GetTypeInfo()
            .GetDeclaredField(enumValue.ToString())
            .GetCustomAttribute< T>();
    }
}
 
Destoon分类属性筛选,自定义分类属性筛选搜索实现

解决方案

而不是找的成员的,你也许应该寻找专门用于各个领域。如果这是不可用的键入在WinRT中,添加使用的System.Reflection; 和使用 type.GetTypeInfo(),并期待在那里,各种反射面被移动到类型信息。

In a WinRT .NET application (C#) I want to get the custom attributes, that are defined on an enum value. Take the following enum for example:

public enum MyEnum
{
    [Display(Name="Foo")]
    EnumValue1,

    [Display(Name="Bar")]
    EnumValue2
}

Now in "normal" .NET I know that I'm able to obtain the custom attributes of an enum value with enumValue.GetType().GetMember(enumValue.ToString()).

Unfortunately, in WinRT .NET the GetMember() method isn't available on the Type class. Any suggestions how to go with this?

=====================================================

Thanks to Marc below, I found the answer! The following code works to get a specific custom attribute from an enum value in .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>();
    }
}

解决方案

Rather than looking for members, you should perhaps look specifically for fields. If that isn't available on the Type in WinRT, add using System.Reflection; and use type.GetTypeInfo() and look on there too, as various reflection facets are moved to the type-info.