隐式转换为Func

时间:2009-05-27 19:38:09

标签: c# delegates lambda anonymous-methods implicit

假设我有一个简单描述一个函数的接口IMyInterface<T>

public interface IMyInterface<T>
{
    T MyFunction(T item);
}

我可以将其替换为Func<T, T>,但出于语义原因我想要接口。我可以在该接口和Func<T,T>之间定义隐式转换,以便我可以将匿名委托或lambda作为参数传递给接受此接口作为参数的函数,就像我使用Func<T,T>一样代替?

为了演示,使用上面声明的接口,我想要一个这样的函数:

public T TestFunction<T>(IMyInterface myInterface, T value)
{
    return myInterface.MyFunction(value);
}

我可以这样打电话:

TestFunction<string>( x => return x + " world", "hello");

结果将是“你好世界”。

1 个答案:

答案 0 :(得分:3)

由于C#中的接口不能包含运算符的定义(或任何静态方法),我相信答案是 no 。另一种方法是使用一个类(不幸的是,不能抽象,因为静态成员/运算符在这里不比在接口中更好)。这样您就可以定义implicit转换运算符,从而能够精确地使用您指定的类型。

在课程中(如果需要,您可以将其设为virtual),您可以将其定义为以下内容。

public class MyClass<T>
{
    public static implicit operator MyClass<T>(Func<T, T> func)
    {
        return new MyClass<T>() { MyFunction = func };
    }

    public MyClass()
    {
    }

    public Func<T, T> MyFunction
    {
        get;
        set;
    }
}

您在问题中对TestFunction的定义应该与编码时完全相同。

public T TestFunction<T>(IMyInterface myInterface, T value)
{
    return myInterface.MyFunction(value);
}

同样致电TestFunction

TestFunction<string>(x => return x + " world", "hello");

这可能不是你想要的,但它仍然合理地接近,而且很可能是你能得到的最好的。

相关问题