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

时间:2018-11-27 16:46:21

标签: c# reflection

我正在尝试获取具有特定属性和属性的Enum参数的所有类的列表。

在下面查看我的示例。我意识到如何获取具有属性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 个答案:

答案 0 :(得分:1)

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

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;
相关问题