创建从 ENUM 到模型的列表

发布于 2024-12-11 18:30:12 字数 936 浏览 0 评论 0原文

我得到了以下模型代码:

public enum EnumTest
{
  [Description ("Enum Text 1")]
  Value_1 = 1,

  [Description ("Enum Text 2")]
  Value_2 = 2,
}

public List<Fields> listFields = new List<Fields>();

public class Fields
{
  public int Code { get; set;}
  public string Description { get; set;}
}

我得到了一个枚举,我想用枚举值填充我的变量代码,并用相同的枚举描述填充变量描述。我查找了很长时间,但未能使用枚举值/描述将“ListFields”初始化到其构造函数中。

我已经获得了枚举和获取其描述的方法..我发现它很有用,所以我将其留在这里,也许它对某人有用..

 public static string GetDescription(this Enum value)
 {
     return (from m in value.GetType().GetMember(value.ToString())
             let attr =(DescriptionAttribute)m.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault()
             select attr == null ? value.ToString() : attr.Description).FirstOrDefault();
  }

要使用它,您只需要执行以下操作:

String xx = Enum.EnumName.GetDescription();

I got the following model piece of code:

public enum EnumTest
{
  [Description ("Enum Text 1")]
  Value_1 = 1,

  [Description ("Enum Text 2")]
  Value_2 = 2,
}

public List<Fields> listFields = new List<Fields>();

public class Fields
{
  public int Code { get; set;}
  public string Description { get; set;}
}

I got an Enum and I would like to fill my variable CODE with enum value and the variable Description with the same enum description. I looked up a long time and failed to initialize my "ListFields" into its constructor with the enum VALUE/DESCRIPTION.

I already got the enum and the method to get its description.. I found it usefull, so I'll leave it here, maybe it can be useful for someone..

 public static string GetDescription(this Enum value)
 {
     return (from m in value.GetType().GetMember(value.ToString())
             let attr =(DescriptionAttribute)m.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault()
             select attr == null ? value.ToString() : attr.Description).FirstOrDefault();
  }

To use this you just need to do something like this:

String xx = Enum.EnumName.GetDescription();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凌乱心跳 2024-12-18 18:30:12

你必须使用反射。

    public static Fields[] GetEnumFields(Type enumType)
    {
        if (enumType == null)
            throw new ArgumentNullException("enumType");
        if (!enumType.IsEnum)
            throw new ArgumentException("Not an enum");

        FieldInfo[] fieldInfos = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);

        Fields[] result = new Fields[fieldInfos.Length];
        for (int i = 0; i < fieldInfos.Length; ++i)
        {
            FieldInfo field = fieldInfos[i];

            int value = (int)field.GetValue(null);

            DescriptionAttribute attrib = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            string desc = attrib != null ? attrib.Description : field.Name;

            result[i] = new Fields(value, desc);
        }

        return result;
    }

    public class Fields
    {
        private int value;
        private string description;

        public int Value
        {
            get { return this.value; }
        }

        public string Description
        {
            get { return this.description; }
        }

        public Fields(int value, string description)
        {
            this.value = value;
            this.description = description;
        }
    }

使用它非常简单:

    enum test
    {
        [Description("hello!")]
        ciao,

        www
    }

    static void Main(string[] args)
    {
        foreach (Fields f in GetEnumFields(typeof(test)))
        {
            Console.WriteLine(f.Description);
        }
    }

在我的实现中,当找不到描述属性时,将使用字段名称。

我们还必须说,反射可能很慢,并且如果您经常需要的话,在需要时重建整个数组是浪费时间。
您可以将数组存储在某个地方,这样您就可以只计算一次并将其缓存起来。
当然,正如我所说,只有当您经常需要这个只读列表时,这才有意义。

You have to use reflection.

    public static Fields[] GetEnumFields(Type enumType)
    {
        if (enumType == null)
            throw new ArgumentNullException("enumType");
        if (!enumType.IsEnum)
            throw new ArgumentException("Not an enum");

        FieldInfo[] fieldInfos = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);

        Fields[] result = new Fields[fieldInfos.Length];
        for (int i = 0; i < fieldInfos.Length; ++i)
        {
            FieldInfo field = fieldInfos[i];

            int value = (int)field.GetValue(null);

            DescriptionAttribute attrib = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            string desc = attrib != null ? attrib.Description : field.Name;

            result[i] = new Fields(value, desc);
        }

        return result;
    }

    public class Fields
    {
        private int value;
        private string description;

        public int Value
        {
            get { return this.value; }
        }

        public string Description
        {
            get { return this.description; }
        }

        public Fields(int value, string description)
        {
            this.value = value;
            this.description = description;
        }
    }

To use it is quite simple:

    enum test
    {
        [Description("hello!")]
        ciao,

        www
    }

    static void Main(string[] args)
    {
        foreach (Fields f in GetEnumFields(typeof(test)))
        {
            Console.WriteLine(f.Description);
        }
    }

In my implementation when a descriptionattribute is not found, field name is used.

We must also say that reflection can be slow and rebuilding the entire array when you need it is a waste of time, if you need it often.
You can store the array somewhere so you can compute it only once and keep it cached.
This of course and as I said, makes sense only if you need this readonly list very often.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文