在程序集中,我想获取特定类属性的所有实例。换句话说,我想拥有具有特定属性的类列表。
通常,您将拥有一个可以使用GetCustomAttributes
方法获取属性的类。
是否可以列出具有特定属性的人员?
答案 0 :(得分:3)
public static IEnumerable<Type> GetTypesWithMyAttribute(Assembly assembly)
{
foreach(Type type in assembly.GetTypes())
{
if (Attribute.IsDefined(type, typeof(MyAttribute)))
yield return type;
}
}
或者:
public static List<Type> GetTypesWithMyAttribute(Assembly assembly)
{
List<Type> types = new List<Type>();
foreach(Type type in assembly.GetTypes())
{
if (type.GetCustomAttributes(typeof(MyAttribute), true).Length > 0)
types.Add(type);
}
return types;
}
Linq VS我的方法基准(100000次迭代):
Round 1
My Approach: 2088ms
Linq Approach 1: 7469ms
Linq Approach 2: 2514ms
Round 2
My Approach: 2055ms
Linq Approach 1: 7082ms
Linq Approach 2: 2149ms
Round 3
My Approach: 2058ms
Linq Approach 1: 7001ms
Linq Approach 2: 2249ms
基准代码:
[STAThread]
public static void Main()
{
List<Type> list;
Stopwatch watch = Stopwatch.StartNew();
for (Int32 i = 0; i < 100000; ++i)
list = GetTypesWithMyAttribute(Assembly.GetExecutingAssembly());
watch.Stop();
Console.WriteLine("ForEach: " + watch.ElapsedMilliseconds);
watch.Restart();
for (Int32 i = 0; i < 100000; ++i)
list = GetTypesWithMyAttributeLinq1(Assembly.GetExecutingAssembly());
Console.WriteLine("Linq 1: " + watch.ElapsedMilliseconds);
watch.Restart();
for (Int32 i = 0; i < 100000; ++i)
list = GetTypesWithMyAttributeLinq2(Assembly.GetExecutingAssembly());
Console.WriteLine("Linq 2: " + watch.ElapsedMilliseconds);
Console.Read();
}
public static List<Type> GetTypesWithMyAttribute(Assembly assembly)
{
List<Type> types = new List<Type>();
foreach (Type type in assembly.GetTypes())
{
if (Attribute.IsDefined(type, typeof(MyAttribute)))
types.Add(type);
}
return types;
}
public static List<Type> GetTypesWithMyAttributeLinq1(Assembly assembly)
{
return assembly.GetTypes()
.Where(t => t.GetCustomAttributes().Any(a => a is MyAttribute))
.ToList();
}
public static List<Type> GetTypesWithMyAttributeLinq2(Assembly assembly)
{
return assembly.GetTypes()
.Where(t => Attribute.IsDefined(t, typeof(MyAttribute)))
.ToList();
}
答案 1 :(得分:2)
您可以使用reflection执行此操作。这将为您提供当前程序集中具有List<Type>
的所有类型的MyAttribute
。
using System.Linq;
using System.Reflection;
// ...
var asmbly = Assembly.GetExecutingAssembly();
var typeList = asmbly.GetTypes().Where(
t => t.GetCustomAttributes(typeof (MyAttribute), true).Length > 0
).ToList();
答案 2 :(得分:1)
var list = asm.GetTypes()
.Where(t => t.GetCustomAttributes().Any(a => a is YourAttribute))
.ToList();
答案 3 :(得分:0)
如果没有代码示例,则假设您有List<Type>
或Assembly
。
public List<Type> TypesWithAttributeDefined(Type attribute)
{
List<Type> types = assembly.GetTypes();
return types.Where(t => Attribute.IsDefined(t, attribute)).ToList();
}