代码之家  ›  专栏  ›  技术社区  ›  aherrick

C#获取具有特定属性参数的所有类的列表[重复]

  •  0
  • aherrick  · 技术社区  · 6 年前

    我试图得到一个所有类的列表,其中包含一个特定的属性和该属性的枚举参数。

    查看下面的示例。我实现了如何获取具有属性的所有类 GenericConfig ,但是,如何对参数进行过滤?

    namespace ConsoleApp1
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                // get me all classes with Attriubute GenericConfigAttribute and Parameter Type1
                var type1Types =
                        from type in Assembly.GetExecutingAssembly().GetTypes()
                        where type.IsDefined(typeof(GenericConfigAttribute), false)
                        select type;
    
                Console.WriteLine(type1Types);
            }
        }
    
        public enum GenericConfigType
        {
            Type1,
            Type2
        }
    
        // program should return this class
        [GenericConfig(GenericConfigType.Type1)]
        public class Type1Implementation
        {
        }
    
        // program should not return this class
        [GenericConfig(GenericConfigType.Type2)]
        public class Type2Implementation
        {
        }
    
        [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
        public class GenericConfigAttribute : Attribute
        {
            public GenericConfigType MyEnum;
    
            public GenericConfigAttribute(GenericConfigType myEnum)
            {
                MyEnum = myEnum;
            }
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   DavidG    6 年前

    您可以将其添加到查询中:

    where type.GetCustomAttribute<GenericConfigAttribute>().MyEnum == GenericConfigType.Type1
    

    例如:

    var type1Types =
        from type in Assembly.GetExecutingAssembly().GetTypes()
        where type.IsDefined(typeof(GenericConfigAttribute), false)
        where type.GetCustomAttribute<GenericConfigAttribute>().MyEnum 
            == GenericConfigType.Type1
        select type;
    

    或稍微简化(更安全):

    var type1Types =
        from type in Assembly.GetExecutingAssembly().GetTypes()
        where type.GetCustomAttribute<GenericConfigAttribute>()?.MyEnum 
            == GenericConfigType.Type1
        select type;
    

    如果需要处理同一类型上的多个属性,可以执行以下操作:

    var type1Types =
        from type in Assembly.GetExecutingAssembly().GetTypes()
        where type.GetCustomAttributes<GenericConfigAttribute>()
            .Any(a => a.MyEnum == GenericConfigType.Type1)
        select type;