C# C获取具有特定属性参数的所有类的列表
我试图得到一个所有类的列表,其中包含一个特定的属性和该属性的枚举参数 查看下面的示例。我意识到如何使用属性GenericConfig获取所有类,但如何过滤参数C# C获取具有特定属性参数的所有类的列表,c#,reflection,C#,Reflection,我试图得到一个所有类的列表,其中包含一个特定的属性和该属性的枚举参数 查看下面的示例。我意识到如何使用属性GenericConfig获取所有类,但如何过滤参数 namespace ConsoleApp1 { internal class Program { private static void Main(string[] args) { // get me all classes with Attriubute Gener
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;
}
}
}
您可以将其添加到查询中:
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;
您不能将特定类型强制转换为top并访问其成员吗?我不明白你们所说的参数筛选是什么意思。还有一件事需要考虑:GenericConfigAttribute是AllowMultiple=true,这意味着如果一个类上有多个属性,它将抛出一个模糊的UsMatchException。@YeldarKurmangaliyev Fair point,也为这种情况添加了一些内容。