简体   繁体   English

是否有更快/更好的方法来获取在C#中应用属性的方法

[英]Is there a quicker/better way to get Methods that have attribute applied in C#

I have a marker interface something like this: 我有一个这样的标记界面:

[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
public class MyAttribute : Attribute
{
}

And i want to apply it to methods on different classes in different assemblies... 我想将它应用于不同程序集中不同类的方法...

Then I want to Get a MethodInfo for all methods that have this attribute applied. 然后我想为所有应用了此属性的方法获取MethodInfo。 I need to search the whole AppDomain and get a reference to all these methods. 我需要搜索整个AppDomain并获取所有这些方法的引用。

I know we can get all types and then get all methods, but is there a quicker/better way to do this? 我知道我们可以获得所有类型然后获得所有方法,但有更快/更好的方法来做到这一点吗? ... or is this the quickest manner to get the information I need? ......或者这是获取我需要的信息的最快方式吗?

(I'm using ASP.NET MVC 1.0, C#, ./NET 3.5) (我正在使用ASP.NET MVC 1.0,C#,。/ NET 3.5)

Thanks heaps! 谢谢堆!

Ultimately, no - you have to scan them. 最终,不 - 你必须扫描它们。 LINQ makes it fairly pain-free though. 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;

Note this only scans loaded assemblies "as is". 请注意,这仅按“原样”扫描加载的程序集。

One thing you should consider is an additional attribute that you can apply to a class/struct, indicating that zero or more methods of that type are marked. 您应该考虑的一件事是可以应用于类/结构的附加属性,表示标记了该类型的零个或多个方法。 That should give you at least an order of magnitude improvement in performance. 这应该会使您的性能至少提高一个数量级。

If the attribute is user-defined (not built in to the .NET framework), then when you're enumerating the assemblies to get the types, you should skip framework assemblies such as mscorlib and System. 如果属性是用户定义的(不是内置于.NET框架中),那么当您枚举程序集以获取类型时,应跳过框架程序集,如mscorlib和System。

If you really need the performance gain, do as Marc suggested and then cache the results in a file. 如果您确实需要性能提升,请按照Marc的建议进行操作 ,然后将结果缓存到文件中。 The next time the application load, if the cached file exists, it can load the appropriate method without parsing every assemblies. 下次应用程序加载时,如果缓存文件存在,它可以加载适当的方法而无需解析每个程序集。

Here is an example of a possible cache file: 以下是可能的缓存文件的示例:

<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>

I've searched for this a few weeks ago as well. 我也在几周前搜索过这个。 I think there is no easier way. 我认为没有更简单的方法。
You might be able to spiffy it up a bit with LINQ. 您可以使用LINQ轻松一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM