获取程序集中所有可序列化类型的代码示例:
public IEnumerable<Type> GetTypesWithAttribute(Assembly assembly)
{
return assembly.GetTypes()
.Where(type => type.IsDefined(typeof(SerializableAttribute), false));
}
Run Code Online (Sandbox Code Playgroud)
IsDefined()接收的第二个参数是是否应该在基类型上查找属性.
查找所有类型的用法示例MyDecorationAttribute:
public class MyDecorationAttribute : Attribute{}
[MyDecoration]
public class MyDecoratedClass{}
[TestFixture]
public class DecorationTests
{
[Test]
public void FindDecoratedClass()
{
var currentAssembly = Assembly.GetExecutingAssembly();
var typesWithAttribute = GetTypesWithAttribute(currentAssembly);
Assert.That(typesWithAttribute,
Is.EquivalentTo(new[] {typeof(MyDecoratedClass)}));
}
public IEnumerable<Type> GetTypesWithAttribute(Assembly assembly)
{
return assembly.GetTypes()
.Where(type => type.IsDefined(typeof(MyDecorationAttribute), false));
}
}
Run Code Online (Sandbox Code Playgroud)