开发者

Create delegate for property acessor obtained via reflection when property type unknown

开发者 https://www.devze.com 2023-04-01 11:33 出处:网络
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?

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消