【问题标题】:Create delegate for property acessor obtained via reflection when property type unknown当属性类型未知时,为通过反射获得的属性访问器创建委托
【发布时间】:2011-08-30 07:17:33
【问题描述】:

在 .NET 2.0(使用 C# 3.0)中,当我在编译时不知道其类型时,如何为通过反射获得的属性访问器创建委托?

例如如果我有int 类型的属性,我可以这样做:

Func<int> getter = (Func<int>)Delegate.CreateDelegate(
    typeof(Func<int>),
    this, property.GetGetMethod(true));
Action<int> setter = (Action<int>)Delegate.CreateDelegate(
    typeof(Action<int>),
    this, property.GetSetMethod(true));

但如果我在编译时不知道该属性是什么类型,我不知道该怎么做。

【问题讨论】:

  • 不确定,但以下问题看起来相关:stackoverflow.com/questions/773099/…
  • Func&lt;T&gt; is .NET 3.5.... 这是自定义的Func&lt;T&gt;
  • @Marc Gravell - Whoops 实际上是在一个针对错误平台的临时项目中玩耍,但它确实适用于 .NET 2.0 中的自定义 Func

标签: c# reflection delegates


【解决方案1】:

你需要的是:

Delegate getter = Delegate.CreateDelegate(
    typeof(Func<>).MakeGenericType(property.PropertyType), this,
    property.GetGetMethod(true));
Delegate setter = Delegate.CreateDelegate(
    typeof(Action<>).MakeGenericType(property.PropertyType), this,
    property.GetSetMethod(true));

然而,如果你这样做是为了提高性能,你仍然会做不到,因为你需要使用DynamicInvoke(),这是slooow。您可能想查看元编程来编写一个接受/返回object 的包装器。或者查看为您执行此操作的 HyperDescriptor。

【讨论】:

  • @Till 如果您的意思是接受的答案...如果您事先不知道类型,您将不得不使用MakeGenericMethod();然后它使用反射创建一个委托立即使用一次并丢弃。坦率地说,在那个例子中,原始反射 (GetValue()/SetValue()) 会更好。
  • @Marc Gravel - 是的,试图这样做是为了提高性能。当我有更多时间时,我会检查 HyperDescriptor - 看起来很棒。
  • @Ergwun 如果您需要更轻量级的东西,我可以告诉您实现类似目标的其他 3 种方法;让我知道。 ILGenerator 跃入脑海
  • @Ergwun 稍后会添加一些内容
猜你喜欢
  • 2012-06-04
  • 2018-05-10
  • 2011-04-09
  • 2011-08-18
  • 2023-03-31
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多