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?

+6
source share
3 answers

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)); 
+9
source

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.

+9
source

You can create a lambda, as JaredPar suggests, or pass it to the constructor of another:

 Func<int, string> f1 = i => i.ToString(); Function<int, string> f2 = new Function<int, string>(f1); 
+8
source

Source: https://habr.com/ru/post/909135/


All Articles