从 MethodInfo 创建委托时出错

Error when creating a delegate from a MethodInfo

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

string ent = c.GetType().GetProperty(prop).GetGetMethod().Invoke(c, null).ToString();

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

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

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));

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

问题是我得到以下异常 "the target method cannot be bound to since its signature or security transparency is not compatible with the delegate type"。我错过了什么?

这一行是问题所在:

Delegate.CreateDelegate(typeof(Func<TestClass, string>), test, method);

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

Delegate.CreateDelegate(typeof(Func<TestClass, string>), method);

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