Joe*_*orn 5 c# lambda delegates anonymous-methods implicit
假设我有一个IMyInterface<T>简单描述一个函数的接口:
public interface IMyInterface<T>
{
T MyFunction(T item);
}
Run Code Online (Sandbox Code Playgroud)
我可以用这个替换它Func<T, T>,但是出于语义原因我想要接口.我可以在该接口之间定义隐式转换,Func<T,T>以便我可以将匿名委托或lambda作为参数传递给接受此接口作为参数的函数,就像我曾经使用过一样Func<T,T>吗?
为了演示,使用上面声明的接口我想要一个这样的函数:
public T TestFunction<T>(IMyInterface myInterface, T value)
{
return myInterface.MyFunction(value);
}
Run Code Online (Sandbox Code Playgroud)
我可以像这样打电话:
TestFunction<string>( x => return x + " world", "hello");
Run Code Online (Sandbox Code Playgroud)
结果将是"你好世界".
由于 C# 中的接口不能包含运算符的定义(或任何静态方法),我相信答案是否定的。另一种方法是使用类(不幸的是,不能是抽象的,因为静态成员/运算符在这里并不比在接口中更好)。这将允许您定义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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您问题中的定义TestFunction应该与您编码的完全一样。
public T TestFunction<T>(IMyInterface myInterface, T value)
{
return myInterface.MyFunction(value);
}
Run Code Online (Sandbox Code Playgroud)
同样,调用TestFunction:
TestFunction<string>(x => return x + " world", "hello");
Run Code Online (Sandbox Code Playgroud)
这可能不是您正在寻找的,但它仍然相当接近,而且很可能是您能够获得的最好的。
| 归档时间: |
|
| 查看次数: |
1606 次 |
| 最近记录: |