【问题标题】:How to refer to attributes in enums?如何引用枚举中的属性?
【发布时间】:2013-03-17 07:37:23
【问题描述】:

如何引用enums 中的属性?

如果我有以下enum 类型,如何引用该枚举类型的特定值的属性?

public enum PersonGender
{
    Unknown = 0,
    Male = 1,
    Female = 2,
    Intersex = 3,
    Indeterminate = 3,

    [EnumMember("Not Stated")]
    NonStated = 9,

    [EnumMember("Inadequately Described")]
    InadequatelyDescribed = 9
}

【问题讨论】:

  • 也许您应该在帖子中添加更多信息,而不仅仅是对答案投反对票。
  • 顺便说一句,如果您使用 System.Runtime.Serialization.EnumMemberAttribute,那么它应该以这种方式应用[EnumMember(Value = "Not Stated")]。你有两个等于 9 的值。
  • @user2154065 他没有,两个第一个回答者互相反对
  • @ofstream 不,我是第一个回答者。我没有对任何人投反对票。

标签: c# .net vb.net enums attributes


【解决方案1】:

以下代码使用.Net 4.5扩展方法GetCustomAttribute获取字段的自定义属性

Type enumType = typeof(PersonGender);
var value = enumType.GetField(PersonGender.NonStated.ToString())
                    .GetCustomAttribute<EnumMemberAttribute>().Value; 
// returns "Not Stated"

当然你应该为字段和自定义属性添加空检查

【讨论】:

  • Error 1 'System.Reflection.FieldInfo' does not contain a definition for 'GetCustomAttribute' and no extension method 'GetCustomAttribute' accepting a first argument of type 'System.Reflection.FieldInfo' could be found (are you missing a using directive or an assembly reference?)
  • @IswantoSan 您正在使用旧框架。这不是拒绝答案的理由
  • 没错,你必须使用旧的框架。该方法存在。
  • @lazyberezovsky:对不起,我的错,我只是再次检查,我使用的是 .NET 4.0。
【解决方案2】:

您可以使用Reflection

例如:

    class EnumMemberAttribute : Attribute
    {
        private String name;

        public String Name
        {
            get { return this.name; }
            set { this.name = value; }
        }

        public EnumMemberAttribute(String name)
        {
            this.name = name;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(PersonGender);
            MemberInfo[] members = type.GetMember(PersonGender.NonStated.ToString());
            Object[] attributes = members[0].GetCustomAttributes(typeof(EnumMemberAttribute),
                false);
            Console.WriteLine(((EnumMemberAttribute)attributes[0]).Name);            
        }
    } 

【讨论】:

    【解决方案3】:

    首先,将 InadequatelyDescribed 设置为 NonStated 以外的其他值。

    其次,EnumMembers 的正确语法是

    [EnumMember(Value = "Not Stated")]
    

    这是解决方案 - 在 .NET 4.0 和 4.5 中工作:

    PersonGender pg = PersonGender.InadequatelyDescribed;
    string pgName = Enum.GetName(typeof(PersonGender), pg);
    
    var t = typeof(PersonGender);
    var info = t.GetMember(pgName);
    var att = info[0].GetCustomAttributes(typeof(EnumMemberAttribute), false);
    
    if (att.Length > 0)
    {
        Console.WriteLine(((EnumMemberAttribute)att[0]).Value);
    }
    else
    {
        Console.WriteLine(pgName);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-16
      • 2022-01-09
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多