簡體   English   中英

使用GetMethods獲取返回特定類型的方法

[英]Getting methods that return a specific type using GetMethods

我正在使用以下方法將comboBox中類中方法名稱的列表插入。

Type t = typeof(Functions);
// public instance methods 
MethodInfo[] methods = t.GetMethods(BindingFlags.Static | BindingFlags.Public);
var methodsNames = methods.Select(i => i.Name).ToArray();
// add them to combobox
comboBox1.Items.AddRange(methodsNames);

我希望它只包含返回特定類型(例如int)的那些。

如果我有那些​​方法:

    public static int CountSameSizes(BinTreeNode<string> BT)
    public static string CountLeaves(BinTreeNode<string> BT)
    public static string CountAtLeastOneLeaf(BinTreeNode<string> BT)

我希望它只返回第一個。

t.GetMethods(BindingFlags.Static | BindingFlags.Public).Cast<MethodInfo>()
    .Where(method => method.ReturnType == typeof(int))

嘗試這個:

   public IEnumerable<string> GetMethodsOfReturnType(Type cls, Type ret)
    {
       var methods = cls.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
       var retMethods = methods.Where(m => m.ReturnType.IsSubclassOf(ret) || m.ReturnType == ret)
                               .Select(m => m.Name);
       return retMethods;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM