c# - 使用反射查找具有自定义属性的方法

标签 c# reflection custom-attributes

我有一个自定义属性:

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();
         }
     }
}

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

最佳答案

你的代码是完全错误的。
您正在遍历每个具有该属性的类型,这将找不到任何类型。

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

例如:

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

关于c# - 使用反射查找具有自定义属性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3467765/

相关文章:

C# 使用私有(private) double 函数来计算距离

java - hibernate 实现。我们要支付反射惩罚吗?

vb.net - 反射 - 类内数组的 SetValue?

c# - 将属性约束为给定类型的属性

C# Generic - 任何声明 T 具有属性的方法?

c# - 属性类如何工作?

c# - 如何在通用应用程序中设置窗口大小?

c# - 如何在 phantomjsdriver selenium c# 中启用 cookie?

java - 使用Java反射,我可以访问私有(private)静态嵌套类类型的私有(private)字段吗?

c# - 在 OnActionExecuting 中获取预期的 Action 参数类型