Hi astrovirgin,
There are couple of delicate moments you need to know as well.
First, let me give you a bit more universal code I meant when I saw your question:
using System;
using System.Reflection;
using MethodList =
System.Collections.Generic.List<System.Reflection.MethodInfo>;
using OverloadingDictionary =
System.Collections.Generic.Dictionary<
string,
System.Collections.Generic.List<System.Reflection.MethodInfo>>;
public class TypeReflector {
public TypeReflector(Type type) { this.Type = type; }
public OverloadingDictionary ClassifyMethodsByName(
BindingFlags flags) {
OverloadingDictionary dict = new OverloadingDictionary();
MethodInfo[] methods = this.Type.GetMethods(flags);
foreach (MethodInfo method in methods) {
MethodList methodList;
if (!dict.TryGetValue(method.Name, out methodList))
methodList = new MethodList();
methodList.Add(method);
}
return dict;
}
Type Type;
}
In this code, if we call
ClassifyMethodsByName
, we can obtain all methods classified in a dictionary by the name key, and the value is a list of methods overloaded under this name. So, the number of overloaded method is simply a list's
Count
:
public static int OverloadingCount(OverloadingDictionary dictionary, string name) {
MethodList methodList;
if (!dictionary.TryGetValue(name, out methodList))
return 0;
else
return methodList.Count;
}
All the information on parameters (and a lot more) can be taken from
MethodInfo
(see Microsoft help -- very clear).
Now, one delicate moment is the parameter
BindingFlags flags
. Many developers was struggling about missing members (not
only methods, but any other) simply because
Type.GetMethods()
without
BindingFlags
parameter returns only subset of a methods (only public and non-static), not all methods. Same story with other kinds of members.
If you need all methods, you need the following:
var dictionary = ClassifyMethodsByName(
BindingFlags.Instance | BindingFlags.Static |
BindingFlags.Public | BindingFlags.NonPublic);
If you don't use
BindingFlags.Instance
, only static members are returned; if you don't use
BindingFlags.Static
, only non-static members are returned;
BindingFlags.NonPublic
adds protected and private ones, etc. There are more different flags, but they are used in different Reflection methods.
Another delicate aspect is inherited members. The Reflection methods we are discussing never list inherited methods (nor any other inherited members).
(Nobody remembered about those, huh?)
To obtain inherited members, one need to collect them recursively.
First, we need a base type:
Type baseType = this.Type.BaseType;
Now,
baseType
should call recursively call some method collecting members. The recursion must end when
Type.BaseType
returns
null
.
As I understand, in your problem inherited methods should be counted exactly as any others, because you say you will use this data to call methods (Invoke). So, you will need to take care about those.
Thank you. Best wishes in New Year!