lundi 21 juin 2021

How do I compile a delegate [duplicate]

I wish to compile a reflected delegate, but I fail miserably with the following exception:

System.ArgumentException: Cannot bind to the target method because its signature is not compatible with that of the delegate type.
   at System.Delegate.CreateDelegate(Type type, MethodInfo method, Boolean throwOnBindFailure)
   at wergwg.Program.Main(String[] args) in

This exception implies that the signature of the MethodInfo provided differs from the delegate I wish to compile it as (Func<TimeSpan, Int64>. Which just is not the case, I invite you all to hop into the debugger and validate, that the property getter of TimeSpan.Ticks indeed consumes a TimeSpan and returns a Int64 or long. Which in Func syntax is equal to Func<TimeSpan, Int64> yet the following code throws a runtime-exception.

TimeSpan ts = TimeSpan.FromMinutes(5);

PropertyInfo ticksProperty = typeof(TimeSpan).GetProperty(nameof(TimeSpan.Ticks));
MethodInfo getTicksMethod = ticksProperty.GetGetMethod(false);
Console.WriteLine(getTicksMethod.Invoke(ts, Array.Empty<object>()));
Func<TimeSpan, Int64> getTicks = (Func<TimeSpan, Int64>)Delegate.CreateDelegate(typeof(Func<TimeSpan, Int64>), getTicksMethod, true);
Console.WriteLine(getTicks(ts));

here is a dotnetfiddle link.


I face the same issue with all instances where I try to compile a reflected delegate, be it from a property, or a method. So I conclude that I am doing something wrong, please educate me in what exactly I am missing and how to "fix" the code above.

Thank you for your time, cheers.





Aucun commentaire:

Enregistrer un commentaire