从 MethodInfo 创建委托时出错

Dan*_*ori 0 c# delegates func

我在另一个问题上得到了一个建议,以替换这段代码:

string ent = c.GetType().GetProperty(prop).GetGetMethod().Invoke(c, null).ToString();
Run Code Online (Sandbox Code Playgroud)

使用可以做同样事情的委托(但在性能方面应该快得多)。

这是我到目前为止的想法:

TestClass test = new TestClass (){DummyProp= "appo"};
string prop = "DummyProp";
MethodInfo method = typeof(TestClass ).GetProperty(prop).GetGetMethod();

Func<TestClass , string> getter= (Func<TestClass , string>)
   Delegate.CreateDelegate(typeof(Func<TestClass , string>), test, method);
Console.WriteLine(getter(test));
Run Code Online (Sandbox Code Playgroud)

我想要做的是在运行时获取 实例中属性的值TestClass,该属性可以是其中的多个属性之一,需要哪个属性取决于某些条件

问题是我收到以下异常“无法绑定目标方法,因为其签名或安全透明度与委托类型不兼容”。我错过了什么?

Jon*_*eet 5

这一行是问题:

Delegate.CreateDelegate(typeof(Func<TestClass, string>), test, method);
Run Code Online (Sandbox Code Playgroud)

您正在尝试创建一个开放委托,即一个未绑定到任何特定实例的委托 - 但您正在传递该实例。如果您将其更改为:

Delegate.CreateDelegate(typeof(Func<TestClass, string>), method);
Run Code Online (Sandbox Code Playgroud)

然后它将创建一个适当的开放委托。