I am trying to create a delegate for setting a property value of a generic, but I am getting an error: Error binding to target method
when I try to execute the following code:
Action<T, object> setValue = (Action<T, object>) Delegate.CreateDelegate(
typeof(Action<T, object>), null, property.GetSetMethod());
Is this even possible?
Yes it is possible, you're just trying to create a delegate of the wrong type. The set method of a property only takes one argument, the value you're going to set. Also since its an instance method, you must pass the target object you want it to be bound to in the CreateDelegate call.
Example:
I think you want this:
or
EDIT
To illustrate the assumed poorer performance of this answer compared to the accepted answer, assume this method:
MerickOWA's answer uses reflection in the
GetSetter
method, so we assume that theGetSetter
method takes more time to execute, in his approach. This answer uses reflection each time we callsetValue.Invoke
, so we assume that takes more time to execute in this answer. If we assume the number of items in the sequence is large, MerickOWA's answer should require less time to execute.For example, let's say that MerickOWA's GetSetter method takes X milliseconds more than mine to execute, while my setValue delegate takes Y milliseconds more than his. If there are N items in the sequence, then my solution should be slower than his by (N * Y - X) milliseconds.
It depends. In my answer I assume two things:
Because your property is a non-static, there are two possibilies:
A function to create such "normal" delegate is created as follows:
And in use (assuming the property type is of type int):
A function to create an open delegate:
And in use: