【问题标题】:Find methods that have custom attribute using reflection使用反射查找具有自定义属性的方法
【发布时间】:2011-03-28 22:06:49
【问题描述】:

我有一个自定义属性:

public class MenuItemAttribute : Attribute
{
}

还有一个有几个方法的类:

public class HelloWorld
{
    [MenuItemAttribute]
    public void Shout()
    {
    }

    [MenuItemAttribute]
    public void Cry()
    {
    }

    public void RunLikeHell()
    {
    }
}

我怎样才能只获得用自定义属性修饰的方法?

到目前为止,我有这个:

string assemblyName = fileInfo.FullName;
byte[] assemblyBytes = File.ReadAllBytes(assemblyName);
Assembly assembly = Assembly.Load(assemblyBytes);

foreach (Type type in assembly.GetTypes())
{
     System.Attribute[] attributes = System.Attribute.GetCustomAttributes(type);

     foreach (Attribute attribute in attributes)
     {
         if (attribute is MenuItemAttribute)
         {
             //Get me the method info
             //MethodInfo[] methods = attribute.GetType().GetMethods();
         }
     }
}

我现在需要的是获取方法名,返回类型,以及它接受的参数。

【问题讨论】:

    标签: c# reflection custom-attributes


    【解决方案1】:

    您的代码完全错误。
    您正在循环遍历具有该属性的每个 type,它不会找到任何类型。

    您需要遍历每种类型的每个方法并检查它是否具有您的属性。

    例如:

    var methods = assembly.GetTypes()
                          .SelectMany(t => t.GetMethods())
                          .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0)
                          .ToArray();
    

    【讨论】:

    • 我是不是在前面做这事?因为现在我查找所有属性,然后尝试获取关联的方法
    • 我在你的课上试过了;这个对我有用。您是否在寻找合适的组件?
    • doh...更改了一些代码以使 stackoverflow 阅读器变得简单...从未将其改回...thanx...您的正确
    • @Tom: GetCustomAttributes() 无论如何都会返回一个数组,所以.Any() 无济于事。
    • 对当前正在执行的程序集使用 Assembly.GetExecutingAssembly()
    【解决方案2】:
    Dictionary<string, MethodInfo> methods = assembly
        .GetTypes()
        .SelectMany(x => x.GetMethods())
        .Where(y => y.GetCustomAttributes().OfType<MethodAttribute>().Any())
        .ToDictionary(z => z.Name);
    

    【讨论】:

      【解决方案3】:
      var classType = new ClassNAME();
      var methods = classType.GetType().GetMethods().Where(m=>m.GetCustomAttributes(typeof(MyAttribute), false).Length > 0)
      .ToArray();
      

      现在您在类classNAME 中拥有了所有具有该属性MyAttribute 的方法。你可以在任何地方调用它。

      public class ClassNAME
      {
          [MyAttribute]
          public void Method1(){}
      
          [MyAttribute]
          public void Method2(){}
      
          public void Method3(){}
      }
      
      class MyAttribute: Attribute { }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-10
        • 1970-01-01
        • 2017-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多