gpt4 book ai didi

c# - 通用 Property.GetSetMethod 的委托(delegate)

转载 作者:太空狗 更新时间:2023-10-29 21:41:11 25 4
gpt4 key购买 nike

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

Action<T, object> setValue = (Action<T, object>) Delegate.CreateDelegate(
typeof(Action<T, object>), null, property.GetSetMethod());

这可能吗?

最佳答案

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

例子:

  var setValue = (Action<T>)Delegate.CreateDelegate( typeof( Action<T> ), target, property.GetSetMethod() );

关于c# - 通用 Property.GetSetMethod 的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8087611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com