[英]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.