Reputation: 9
I am facing one issue in Invoking different methods which are having different types of parameter. For eg. I have 3 methods A, B, C with parameters as follows.
A(string text, int num)
B(bool type, int num2)
C(string text2, boolean type2, int num3)
Now how to invoke these three methods one by one? The method names are fetched as string and stored in an array, and after storing them, the methods needs to be invoked using For Each loop.
Upvotes: 0
Views: 258
Reputation: 50819
You can keep in Dictionary
the method names and parameters as string
and object[]
Dictionary<string, object[]> methodsInfo = new Dictionary<string, object[]>
{
{ "A", new object[] { "qwe", 4 }},
{ "B", new object[] { true, 5 }},
{ "C", new object[] { "asd", false, 42 }}
};
And invoke them using Invoke
from MethodInfo
foreach (KeyValuePair<string, object[]> methodInfo in methodsInfo)
{
GetType().GetMethod(methodInfo.Key).Invoke(this, methodInfo.Value);
}
If the methods are in another class you invoke them like this
Type classType = Type.GetType("namespace.className");
object classObject = classType.GetConstructor(Type.EmptyTypes).Invoke(new object[] { });
foreach (KeyValuePair<string, object[]> methodInfo in methodsInfo)
{
classType.GetMethod(methodInfo.Key).Invoke(classObject, methodInfo.Value);
}
Note: GetConstructor(Type.EmptyTypes)
is for empty constructor, for parameterized constructor (say with int
) use GetConstructor(new[] { typeof(int) }).Invoke(new object[] { 3 }
Upvotes: 2