I've been working in .net 4 and really enjoying the ability to return bespoke functions from a single method e.g:

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:

public delegate<object> FunctionBuilder(object o) 
{ /*nope*/ }

...is not valid syntax..

Is it even possible to return bespoke functions from a method within .net2?

有帮助吗?

解决方案

Is it even possible to return bespoke functions from a method within .net2?

Absolutely, but you need to return a specific delegate type.

The simplest thing is probably to declare your own generic delegates, e.g.

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. We've taken this exact approach in Noda Time (which actually now uses .NET 3.5 anyway) and it's worked fine.

其他提示

You should use this construct.

delegate object MyDelegate(object);

MyDelegate FunctionBuilder()
{

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top