获取枚举值的自定义属性[重复]

时间:2023-01-26 14:48:09

This question already has an answer here:

这个问题在这里已有答案:

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:

在WinRT .NET应用程序(C#)中,我想获取在枚举值上定义的自定义属性。以下面的枚举为例:

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()).

现在在“普通”.NET中,我知道我能够使用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?

不幸的是,在WinRT .NET中,Type类上没有GetMember()方法。有什么建议怎么搭配?

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

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

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:

感谢下面的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>();
    }
}

1 个解决方案

#1


14  

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.

您可能应该专门查看字段,而不是寻找成员。如果在WinRT中的Type上不可用,请使用System.Reflection添加;并使用type.GetTypeInfo()并在那里查看,因为各种反射方面被移动到type-in​​fo。

#1


14  

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.

您可能应该专门查看字段,而不是寻找成员。如果在WinRT中的Type上不可用,请使用System.Reflection添加;并使用type.GetTypeInfo()并在那里查看,因为各种反射方面被移动到type-in​​fo。