Create delegate for property acessor obtained via

2019-05-11 00:25发布

In .NET 2.0 (with C# 3.0), how can I create a delegate for a property accessor obtained via reflection when I don't know its type at compile time?

E.g. if I have property of type int, I can do this:

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));

but if I do not know what type the property is at compile time, I don't know how to do it.

1条回答
forever°为你锁心
2楼-- · 2019-05-11 01:02

What you need is:

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));

however, if you are doing this for performance, you are still going to come up short, since you would need to use DynamicInvoke(), which is slooow. You might want to look at meta-programming to write a wrapper that takes/returns object. Or look at HyperDescriptor which does this for you.

查看更多
登录 后发表回答