如果我这样做,我会枚举我的程序中的所有类型:
List<SerializableAttribute> attributes=new List<SerializableAttribute>() ;
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type type in assembly.GetTypes())
{
attributes.AddRange(
type.GetCustomAttributes(false)
.OfType<SerializableAttribute>()
.ToList());
}
}
Run Code Online (Sandbox Code Playgroud)
.NET dll附带的元数据是否被索引以允许我执行以下操作:
List<SerializableAttribute> attributes = typeof(SerializableAttribute)
.GetClassesIAmDefinedOn();
Run Code Online (Sandbox Code Playgroud)
还有其他选择我不考虑吗?
(SerializableAttribute只是一个例子)
好吧,使用LINQ更多并使用IsDefined至少使代码更好(并获取类型,而不是属性...)
var types = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where Attribute.IsDefined(type, typeof(SerializableAttribute))
select type).ToList();
Run Code Online (Sandbox Code Playgroud)
现在,您询问了效率 - 这需要多长时间?它可以接受多长时间?你经常打电话吗?(这看起来很奇怪.)
还要注意它只包括已经加载的程序集 - 可能有一个尚未加载的引用程序集; 那个没被拿起的重要吗?
这里使用的最有效的方法通常是Attribute.IsDefined(...),虽然在特定情况下[Serializable],type.IsSerializable更快(在这种情况下它实际上不存储为属性 - 它在编译器中有特殊处理,映射到CLI标志).