我有一个自定义属性:
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/