从 lambda 表达式到用户定义类型的隐式转换

Implicit conversion from lambda expression to user-defined type

我想定义从(特定)lambda 表达式到用户定义类型的隐式转换。我尝试了以下方法:

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

然后我尝试了

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

这给出 "Cannot convert lambda expression ... because it is not a delegate type"

相反,有效的是:

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

我想,lambda 表达式没有 'Func' 类型,所以我必须在隐式转换中加入一些不同的东西。

有人可以给我提示吗?

你的解决方法很好。
Lambda 本身没有类型,因此应将它们转换为某种适当的类型。
请参阅 MSDN:

Note that lambda expressions in themselves do not have a type because the common type system has no intrinsic concept of "lambda expression." However, it is sometimes convenient to speak informally of 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.

这就是以下示例无法编译的原因:

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

您已经从 Func<OPTatom, OPTatom, T> 委托类型定义了隐式运算符,并尝试从 lambda 表达式进行转换,这对 C# 编译器来说似乎很奇怪。

而是将 lambda 表达式存储在一些 Func<OPTatom, OPTatom, T> 类型的变量中,然后执行隐式转换。 以下将在这里工作:

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

我创建了演示并且运行良好。

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"));
    }
}

Here 是 dotnetfiddle link 如果您想使用它。