使用反射查找具有自定义属性的方法 [英] Find methods that have custom attribute using reflection

查看:23
本文介绍了使用反射查找具有自定义属性的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义属性:

public class MenuItemAttribute : Attribute
{
}

和一个有几个方法的类:

and a class with a few methods:

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

    [MenuItemAttribute]
    public void Cry()
    {
    }

    public void RunLikeHell()
    {
    }
}

如何只获取用自定义属性修饰的方法?

How can I get only the methods that are decorated with the custom attribute?

到目前为止,我有这个:

So far, I have this:

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

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

What I need now is to get the method name, the return type, as well as the parameters it accepts.

推荐答案

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

Your code is completely wrong.
You are looping through every type that has the attribute, which will not find any types.

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

You need to loop through every method on every type and check whether it has your attribute.

例如:

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

这篇关于使用反射查找具有自定义属性的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆