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

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

问题描述

我有一个自定义属性:

public class MenuItemAttribute : Attribute
{
}

和有一些方法的类:

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.

推荐答案

您code是完全错误的。结果
你是通过每一个循环的键入的具有属性,它不会找到任何类型的。

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天全站免登陆