rPu*_*lvi 0 c# reflection delegates
我需要使用反射调用委托方法,并将方法名称作为字符串传递。
例如,我将传递类名和委托的My.Controls.TestDelegate.myConverterAction位置:TestDelegatemyConverterAction
namespace My.Controls
{
public static class TestDelegate
{
public static CustomConversionHandler myConverterAction = new CustomConversionHandler(doSomething);
private static ulong doSomething(object[] values)
{
return 2;
}
}
}
Run Code Online (Sandbox Code Playgroud)
GetMethod()我想以这种方式使用该方法:
int separator = actionDelegate.LastIndexOf('.');
string className = actionDelegate.Substring(0, separator);
string methodName = actionDelegate.Substring(separator + 1, actionDelegate.Length - className.Length - 1);
var t = Type.GetType(className); //This works
MethodInfo m = t.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static); //This returns null...even with different BindingFlags options
Run Code Online (Sandbox Code Playgroud)
但我获得了一个空引用。我怎么解决这个问题?
由于TestDelegate.myConverterAction是静态字段而不是方法,因此您应该使用以下代码检索它:
FieldInfo info = typeof(TestDelegate).GetField("myConverterAction", BindingFlags.Public | BindingFlags.Static);
object yourField = info.GetValue(null);
Run Code Online (Sandbox Code Playgroud)
为了调用它,您需要使用以下方法获取它的调用方法:
MethodInfo method = yourField.GetType().GetMethod("Invoke");
Run Code Online (Sandbox Code Playgroud)
并Invoke使用以下方法调用该方法MethodInfo.Invoke():
method.Invoke(yourField, new {new object[]{"123"}});
Run Code Online (Sandbox Code Playgroud)