How to simulate a “Func<(Of <(TResult>)>) De

2020-08-10 07:15发布

问题:

I try to use the class from this CodeProject article in VB.NET and with .NET Framework 2.0.

Everything seem to compile except this line Private _workerFunction As Func(Of TResult) and the method header Public Sub New(ByVal worker As Func(Of TResult)).

I can find on MSDN that these new delegates (Func(Of ...) are supported from .NET 3.5.

How can I rewrite that to work in .NET 2.0?

回答1:

Luckily, .NET 2.0 already supports generics, so you can just create your own delegate with the same signature:

public delegate T Func<T>();


回答2:

As Konamiman says, you can declare your own delegate types very easily. On my "versions" page, I have them all declared so you can just cut and paste them:

public delegate void Action();
public delegate void Action<T1, T2>(T1 arg1, T2 arg2);
public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg);
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);

(I haven't avoided scrolling here, as you probably don't want the line breaks in the IDE. Note that Action<T> is part of .NET 2.0, hence its absence above.)



标签: c# .net