当属性类型未知时,通过反射获得属性评估者的委托

时间:2011-08-30 07:17:33

标签: c# reflection delegates

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

E.g。如果我有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));

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

1 个答案:

答案 0 :(得分:2)

您需要的是:

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));
但是,如果你这样做是为了表现,那么你仍然会做空,因为你需要使用{{1>},这是 slooow 。您可能希望查看元编程以编写一个包含/返回DynamicInvoke()的包装器。或者看看HyperDescriptor为你做这件事。

相关问题