简体   繁体   English

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

[英]Find methods that have custom attribute using reflection

I have a custom attribute:我有一个自定义属性:

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.我现在需要的是获取方法名称、返回类型以及它接受的参数。

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.您需要遍历每种类型的每个方法并检查它是否具有您的属性。

For example:例如:

var methods = assembly.GetTypes()
                      .SelectMany(t => t.GetMethods())
                      .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0)
                      .ToArray();
Dictionary<string, MethodInfo> methods = assembly
    .GetTypes()
    .SelectMany(x => x.GetMethods())
    .Where(y => y.GetCustomAttributes().OfType<MethodAttribute>().Any())
    .ToDictionary(z => z.Name);
var classType = new ClassNAME();
var methods = classType.GetType().GetMethods().Where(m=>m.GetCustomAttributes(typeof(MyAttribute), false).Length > 0)
.ToArray();

Now you have all methods with this attribute MyAttribute in class classNAME .现在您在classNAME类中拥有具有此属性MyAttribute所有方法。 You can invoke it anywhere.您可以在任何地方调用它。

public class ClassNAME
{
    [MyAttribute]
    public void Method1(){}

    [MyAttribute]
    public void Method2(){}

    public void Method3(){}
}

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

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