当属性类型未知时,为通过反射获得的属性访问器创建委托

Erg*_*wun 5 c# reflection delegates

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

例如,如果我有 type 属性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));
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 3

你需要的是:

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));
Run Code Online (Sandbox Code Playgroud)

但是,如果您这样做是为了提高性能,那么您仍然会遇到不足,因为您需要使用DynamicInvoke(),这很慢。您可能想看看元编程来编写一个需要/返回的包装器object。或者查看 HyperDescriptor,它可以为您完成此操作。