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:
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/returnsobject. Or look at HyperDescriptor which does this for you.