【问题标题】:foreach on enum with Custom Attributes [duplicate]具有自定义属性的枚举上的 foreach [重复]
【发布时间】:2018-07-28 20:01:28
【问题描述】:

如何迭代枚举并获取属性和值?

public enum TableName {
    [DescriptionWithValue("offline", "create table offline (uid int, date datetime, id int)")]
    Offline,
    [Description("Online","create table online (uid int, date datetime, id int)")]
    online,
    [Description("Amount","create table amount (uid int, date datetime, id int)")]
    amount
}

【问题讨论】:

  • 你是怎么做的? SO 是关于修复你的代码——而不是实现你的想法。请再次查看how to askon-topic,如果您有任何问题,请将您的代码提供为mvce。如果您遇到错误,请将错误消息逐字(逐字)复制并粘贴到您的问题中。除非您需要传达布局错误,否则请避免使用屏幕截图。我们无法将您的图像复制并粘贴到我们的 IDE 中来修复您的代码。
  • Attributesiterate 。我使用了搜索引擎。
  • @PatrickArtner 这是一个编程问题。
  • @PatrickArtner 的意思是让您展示您尝试做的事情。你是如何尝试实现的,你在哪里遇到困难,或者在你尝试时会显示什么错误消息。从那里可以为您指明正确的方向或修复代码,而不是让别人从头开始为您编写代码。

标签: c# linq enums


【解决方案1】:

你的意思是这样的?

    class Program
    {
        static void Main()
        {
            foreach (var field in typeof(TableName).GetFields(BindingFlags.Static | BindingFlags.Public))
            {
                ProcessField(field);
            }
        }

        static void ProcessField(FieldInfo field)
        {
            ProcessD(field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute);
            ProcessDWV(field.GetCustomAttribute(typeof(DescriptionWithValueAttribute)) as DescriptionWithValueAttribute);            
        }

        static void ProcessD(DescriptionAttribute attribute)
        {
            if(attribute != null)
            {
                //...
            }
        }

        static void ProcessDWV(DescriptionWithValueAttribute attribute)
        {
            if (attribute != null)
            {
                //...
            }
        }

【讨论】:

    猜你喜欢
    • 2017-04-02
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2013-02-20
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    相关资源
    最近更新 更多