Implicit conversion from lambda expression to user type

I want to define an implicit conversion from (specific) lambda expressions to a custom type. I tried the following:

public static implicit operator DualElement<T>(Func<OPTatom, OPTatom, T> atomMap) { return new DualElement<T>(e => atomMap(e[0],e[1])); } 

Then i tried

 DualElement<double> dubidu = (i, j) => cost[i, j]; 

which gives "Cannot convert lambda expression ... because it is not a delegate type"

Instead it works:

 DualElement<double> dideldu = (Func<OPTatom, OPTatom, double>)((i, j) => cost[i, j]); 

I assume that lambda expressions are not of type "Func", so I have to put something else in an implicit conversion.

Can someone give me a hint?

+6
source share
2 answers

Your workaround is pretty good.
Lambdas has no type in itself, so they should be dropped to the appropriate type.
See MSDN :

Note that lambda expressions themselves are not of a type , because a general type system does not have an internal concept of a lambda expression. However, sometimes it’s convenient to talk informally about the β€œtype” of a lambda expression. In these cases, the type refers to the delegate type or Expression type to which the lambda expression is converted.

This is why the following example will not compile:

 var func = (i, j) => i + j; 
+3
source

You defined an implicit statement from the delegate type Func<OPTatom, OPTatom, T> and are trying to convert from a lambda expression that seems strange to the C # compiler.

Instead, save the lambda expression in some variable of type Func<OPTatom, OPTatom, T> , and then do the implicit conversion. The following will work here:

 Func<OPTatom, OPTatom, T> temp = (i, j) => cost[i, j]; DualElement<double> dubidu = temp; 

I created a demo and it worked fine.

 public class Program { public static void Main() { Func<string, bool> func = d => true; Process<bool> p = func; //Process<bool> p = d => true; would result in error } } public class Process<T> { public Process(T item) { Item = item; } public T Item { get; set; } public static implicit operator Process<T>(Func<string, T> func) { return new Process<T>(func("jenish")); } } 

There is a dotnetfiddle link here if you want to play with it.

+1
source

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


All Articles