委托Generic Property.GetSetMethod

Cha*_*ams 6 c# generics delegates

我正在尝试创建一个委托来设置泛型的属性值,但我收到一个错误:Error binding to target method当我尝试执行以下代码时:

Action<T, object> setValue = (Action<T, object>) Delegate.CreateDelegate(
    typeof(Action<T, object>), null, property.GetSetMethod());
Run Code Online (Sandbox Code Playgroud)

这甚至可能吗?

Mer*_*OWA 5

是的,这是可能的,您只是想创建一个错误类型的委托。属性的 set 方法只接受一个参数,即您要设置的值。此外,由于它是一个实例方法,您必须在 CreateDelegate 调用中传递您希望它绑定到的目标对象。

例子:

  var setValue = (Action<T>)Delegate.CreateDelegate( typeof( Action<T> ), target, property.GetSetMethod() );
Run Code Online (Sandbox Code Playgroud)