How to convert delegate R function <T, R> (T t) to Func <T, R>?
I have legacy code defined by the following helper
public delegate R Function<T, R>(T t);
But I want to put Func<T,TResult>
casting attempts will not compile
Cannot convert type '
System.Func<T,TResult>
' to 'Rhino.Mocks.Function<T,TResult>
'
Is there a way that not only compiles, but also performs functions at runtime?
The problem is that you are trying to combine two different types of delegates: Func<T, TResult>
and Function<T, TResult>
. Despite the fact that they have the same signature, they differ from each other and, therefore, are incompatible types.
Use lambda to create a transform layer between them.
Func<T, TResult> func = ...; TheMethod(x => func(x));
Jared and Foig are both correct. The third way to do the same is to simply round it:
Func<int, string> func = i => i.ToString(); Function<int, string> function = func.Invoke;
That is, the new delegate is a delegate of the invoke method of the first delegate that has the correct signature.
What needs to be done is annoying in a pinch. If we were developing the runtime today from scratch, knowing that we now know how people use delegate types, I think itβs likely that for each signature there will be either one built-in delegate type (just like there is one βone-dimensional arrayβ integers "" type "), or that there will be a" structural identity "among the types of delegates. The next time you create a type system for a virtual machine, keep this in mind.