Create a delegate for the property owner, obtained by reflecting when the property type is unknown

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

eg. if I have a type property 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 don’t know what type of property is at compile time, I don’t know how to do it.

+3
source share
1 answer

What you need:

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, .

+2