c# - 从枚举中获取 DescriptionAttribute

标签 c# enums

<分区>

我有一个枚举,用于查找协调字符串值。其中一个枚举中有一个空格,因此我试图使用 description 属性来查找该值。找到 DescriptionAttribute 后,我无法转换回公共(public)类。

public class Address
{
   ...blah...more class datatypes here...

    public AddressType Type { get; set; }

    ...blah....

public enum AddressType
{
    FRA = 0,
    JAP = 1,
    MEX = 2,
    CAN = 3,
    [Description("United States")]
    UnitedStates = 4, 

}


 if (Address.Type.ToString() == "UnitedStates")
            {
               Adddress.Type = GetDescription(Address.Type);
            }

private static AddressType GetDescription(AddressType addrType)
    {
        FieldInfo fi = addrType.GetType().GetField(addrType.ToString());
        DescriptionAttribute[] attributes =
        (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute), false);
        return (attributes.Length > 0) ? attributes[0].Description : addrType.ToString();            
    }

在 GetDescription 方法中,如何将其转换回其公共(public)类数据类型“AddressType”,但失败了,因为这里是一个字符串?

最佳答案

恐怕我不能 100% 确定您要的是什么,但以下方法返回提供的 AddressTypestring 描述或名称。

private static string GetDescription(AddressType addrType)
{
    FieldInfo fi = addrType.GetType().GetField(addrType.ToString());
    DescriptionAttribute[] attributes = 
        (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    return (attributes.Length > 0) ? attributes[0].Description : addrType.ToString();            
}

注意返回类型 string

关于c# - 从枚举中获取 DescriptionAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15233780/

相关文章:

enums - 如何在 Fortran 中进行多个枚举类型?

java - 如何反转枚举?

c# - 打开 XML(Microsoft Word): C# Table Justification

c# - 处理数据馈送格式

c# - 使用嵌套选择 LINQ 循环数组

c# - 枚举的扩展方法,而不是枚举的实例

javascript - 可以从相应的整数值获取字符串值 - 类似于 Enum 但不是 Enum - 用于查找

c# - 转换,性能,错误处理

c# - 在C#中使用for循环的完整句子的反词

c - 当您调用包含枚举类型的结构时会发生什么?