我正在努力了解代表团所以我只是写了一个小试试项目; 我有D班:
class D
{
private static void Func1(Object o)
{
if (!(o is string)) return;
string s = o as string;
Console.WriteLine("Func1 going to sleep");
Thread.Sleep(1500);
Console.WriteLine("Func1: " + s);
}
}
Run Code Online (Sandbox Code Playgroud)
并在主要使用中:
MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static);
Delegate d = Delegate.CreateDelegate(typeof(D), inf);
Run Code Online (Sandbox Code Playgroud)
方法info获取正确的信息,但CreateDelegate方法抛出异常,例如,该类型必须从Delegate派生.
我怎么解决这个问题?
如果要为方法创建委托,则Func1需要指定要创建的委托的类型.在这种情况下,您可以使用Action<object>:
MethodInfo inf = typeof(D).GetMethod("Func1", BindingFlags.NonPublic | BindingFlags.Static);
Delegate d = Delegate.CreateDelegate(typeof(Action<object>), inf);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1290 次 |
| 最近记录: |