【问题标题】:C# Get List of All Classes with Specific Attribute Parameter [duplicate]C#获取具有特定属性参数的所有类的列表[重复]
【发布时间】:2019-04-29 11:18:51
【问题描述】:

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

在下面查看我的示例。我知道如何获取属性为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;
        }
    }
}

【问题讨论】:

  • 您不能直接将特定类型投射到顶部并访问其成员吗?我不明白您所说的“过滤参数”是什么意思。

标签: c# reflection


【解决方案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;

【讨论】:

  • 还需要考虑一件事:GenericConfigAttributeAllowMultiple = true,这意味着如果一个类中有多个属性,它将抛出 AmbiguousMatchException
  • @YeldarKurmangaliyev 公平点,也为这种情况添加了一些东西。
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 2013-01-04
  • 2016-03-04
  • 1970-01-01
  • 2012-11-11
  • 2021-09-01
  • 1970-01-01
  • 2010-10-17
相关资源
最近更新 更多