![](/img/trans.png)
[英]Is there a quicker way to declare multiple {get; set;} properties in c#?
[英]Is there a quicker/better way to get Methods that have attribute applied in C#
我有一个这样的标记界面:
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
public class MyAttribute : Attribute
{
}
我想将它应用于不同程序集中不同类的方法...
然后我想为所有应用了此属性的方法获取MethodInfo。 我需要搜索整个AppDomain并获取所有这些方法的引用。
我知道我们可以获得所有类型然后获得所有方法,但有更快/更好的方法来做到这一点吗? ......或者这是获取我需要的信息的最快方式吗?
(我正在使用ASP.NET MVC 1.0,C#,。/ NET 3.5)
谢谢堆!
最终,不 - 你必须扫描它们。 LINQ让它相当无痛。
var qry = from asm in AppDomain.CurrentDomain.GetAssemblies()
from type in asm.GetTypes()
from method in type.GetMethods()
where Attribute.IsDefined(method, typeof(MyAttribute))
select method;
请注意,这仅按“原样”扫描加载的程序集。
您应该考虑的一件事是可以应用于类/结构的附加属性,表示标记了该类型的零个或多个方法。 这应该会使您的性能至少提高一个数量级。
如果属性是用户定义的(不是内置于.NET框架中),那么当您枚举程序集以获取类型时,应跳过框架程序集,如mscorlib和System。
如果您确实需要性能提升,请按照Marc的建议进行操作 ,然后将结果缓存到文件中。 下次应用程序加载时,如果缓存文件存在,它可以加载适当的方法而无需解析每个程序集。
以下是可能的缓存文件的示例:
<attributeCache>
<assembly name='Assembly1' filename='Assembly1.dll' timestamp='02/02/2010'>
<type name='Assembly1.Type1'>
<method name='Method1'/>
</type>
</assembly>
<assembly name='Assembly2' filename='Assembly2.dll' timestamp='02/02/2010' />
</attributeCache>
我也在几周前搜索过这个。 我认为没有更简单的方法。
您可以使用LINQ轻松一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.