.NET 2.0 也支持匿名委托,只是语法比 lambda 更冗长,并且类型推断不起作用。 C# 2.0 中没有扩展方法(尽管您可以使用 C# 3.0 并针对 .NET 2.0 进行编译),它们是 LINQ 的基础并且能够对接口进行操作。
比较:
- .NET 2.0:
delegate(int i) { return (i < 5); }
- .NET 3.5:
i => i < 5
.NET 2.0 也缺少常见的通用委托签名(Func 和 Action),但您也可以轻松地自己定义它们(对于您喜欢的所有参数组合):
public delegate void Action<T>(T item);
public delegate Tresult Func<T, Tresult>(T item);
因此,无论您的链接答案用于模拟匿名接口的任何方法,都可以使用 .NET 2.0 委托来表示,但会增加冗长性。让你问自己:“这真的那么写得更短吗?”
[更新]
如果你的接口是单方法接口,比如:
interface IFoo
{
string Bar(int value);
}
class SomeOtherClass
{
void DoSomething(IFoo foo);
}
那么您可能会完全摆脱它,而只需使用委托:
class SomeOtherClass
{
void DoSomething(Func<int, string> bar);
}
new SomeOtherClass().DoSomething(delegate(int i) { return i.ToString(); });
如果您有一个包含许多方法的接口,您希望能够在许多不同的地方实现内联,您可以使用这样的东西:
interface IFoo
{
string GetSomething();
void DoSomething(int value);
}
// conditional compile, only if .NET 2.0
#if NET_2_0
public delegate void Action<T>(T item);
public delegate Tresult Func<Tresult>();
#endif
class DelegatedFoo : IFoo
{
private readonly Func<string> _get;
private readonly Action<int> _do;
public DelegatedFoo(Func<string> getStuff, Action<int> doStuff)
{
_get = getStuff;
_do = doStuff;
}
#region IFoo members simply invoke private delegates
public string GetSomething()
{ return _get(); }
public void DoSomething(int value)
{ _do(value); }
#endregion
}
这将允许您将代表传递给 DelegatedFoo 内联类:
var delegated = new DelegatedFoo(
delegate() { return ""; }, // string GetSomething()
delegate(int i) { } // void DoSomething(int)
);
使用 .NET 4 C# 4.0 语法,由于 lambdas 和命名参数的语法甜美,它看起来会更干净一些:
var delegated = new DelegatedFoo(
getStuff: () => "",
doStuff: i => { }
);