call compile-time-checked method with dynamic arguments in c#
Ok, this is what I want to do:
public static void CallStaticMethod(Type myType, String methodName, Object[] parameters)
{
MethodInfo m = myType.GetMethod(methodName); // make this compile-time safe
m.Invoke(null, parameters); // methodName method is supposed to be static
}
Now, myType.GetMethod(methodName) can fail at runtime if "methodName" does not exist.
Is there any way to make this compile-time safe? (supposing the parameters are correct)I'd like to call the method somehow like this:
CallStaticMethod(()开发者_StackOverflow社区=>MyType.MyMethod(), Object[] parameters)
notice that this doesn't work since you need to specify the arguments inside the lambda expression.
In other words, I need a compile-time safe handle on a method. I can get one on a type using typeof(), but is it possible for a method?
Use function pointers, that is, delegates. Simple example:
delegate int StringIntParse(string value);
public static int Main(string[] args)
{
StringIntParse p = int.Parse;
Console.WriteLine(p("34"));
Console.WriteLine(p.DynamicInvoke(new object[] { "43" }));
return 0;
}
You can use DynamicInvoke on any delegate, e.g.:
static object InvokeAnyDelegate(Delegate d, params object[] args)
{
return d.DynamicInvoke(args);
}
精彩评论