I have multiple methods, some with optional parameters and some without any. How can i call those methods by only having the function name as a string?
Currently i have this:
public Method method = Method.QuickSort;
public enum Method
{
BubbleSort,
MergeSort,
QuickSort,
InsertionSort,
RadixSortLSD,
CocktailSort,
CombSort,
OddEvenSort
}
MethodInfo mi = this.GetType().GetMethod(method.ToString());
mi.Invoke(this, null);
So, this all works fine, untill i have a function with a optional parameter.. The way i "fixed" it, is like this:
try
{
mi.Invoke(this, null);
}
catch
{
try
{
mi.Invoke(this, new object[] { Type.Missing });
}
catch
{
try
{
mi.Invoke(this, new object[] { Type.Missing, Type.Missing });
}
catch
{
mi.Invoke(this, new object[] { Type.Missing, Type.Missing, Type.Missing });
}
}
}
But this is a terrible "solution", obviously. So my question, how can i create the functionality that i need?(Calling a method by a string name with optional paramaters)
You can determine the number of parameters from the MethodInfo
:
MethodInfo mi = this.GetType().GetMethod("name");
mi.Invoke(this, mi.GetParameters().Select(p => Type.Missing).ToArray());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.