繁体   English   中英

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

[英]Find methods that have custom attribute using reflection

我有一个自定义属性:

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

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

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