[英]Methods that return delegates with .net2
I've been working in .net 4 and really enjoying the ability to return bespoke functions from a single method eg: 我一直在.net 4中工作,并且真正享受从单个方法返回定制功能的能力,例如:
public Func<object, object> FunctionBuilder(object o)
{ /*build functions, woo*/ }
...however this appears very difficult if not impossible to do within .net2 since Func
appears in .net3.5(?) and something like: ...但是,由于
Func
出现在.net3.5(?)中,因此在.net2中这样做似乎非常困难,甚至不是不可能:
public delegate<object> FunctionBuilder(object o)
{ /*nope*/ }
...is not valid syntax.. ...语法无效。
Is it even possible to return bespoke functions from a method within .net2? 甚至可能从.net2中的方法返回定制函数?
Is it even possible to return bespoke functions from a method within .net2?
甚至可能从.net2中的方法返回定制函数?
Absolutely, but you need to return a specific delegate type. 绝对可以,但是您需要返回特定的委托类型。
The simplest thing is probably to declare your own generic delegates, eg 最简单的事情可能是声明您自己的泛型委托,例如
public delegate TResult ProjectFunc<T, TResult>(T arg)
And then: 接着:
public ProjectFunc<object, object> FunctionBuilder(object o)
Then if/when your project moves to .NET 3.5, you can just remove ProjectFunc
and use Func
instead. 然后,如果/当您的项目移至.NET 3.5时,您可以删除
ProjectFunc
并改用Func
。 We've taken this exact approach in Noda Time (which actually now uses .NET 3.5 anyway) and it's worked fine. 我们在Noda Time中采用了这种精确的方法 (现在无论如何现在实际上都使用.NET 3.5),并且运行良好。
You should use this construct. 您应该使用此构造。
delegate object MyDelegate(object);
MyDelegate FunctionBuilder()
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.