试试这个:
打开您的项目,在解决方案资源管理器中右键单击您的项目,导航到“构建”选项卡,在条件编译符号文本框中添加CSHARP2。
声明一个名为 CSharpExtensions.cs 的类:
namespace System
{
#if CSHARP2
public delegate void Action();
public delegate void Action<T>(T t);
public delegate void Action<T, U>(T t, U u);
public delegate void Action<T, U, V>(T t, U u, V v);
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T t);
public delegate TResult Func<T, U, TResult>(T t, U u);
public delegate TResult Func<T, U, V, TResult>(T t, U u, V v);
#endif
}
假设您在 3.5 下编译 没有定义 CSHARP2 符号,您应该能够按预期使用上面的函数:
using System; // includes our new delegates
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static IEnumerable<U> Map<T, U>(IEnumerable<T> input, Func<T, U> f)
{
foreach (T t in input)
{
yield return f(t);
}
}
static void Main(string[] args)
{
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
foreach(String s in Map<int, string>(numbers, delegate(int i) { return String.Format("{0}^2 = {1}", i, i*i); }))
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
}