public class Foo : IList
{
private List _Collection { get; set; } implements IList;
public Foo()
{
_Collection = new List();
}
//这将覆盖委托的执行
// 漂亮的混入和方便的功能
pattern implementation
public int IList.Add(string value)
{
if (!_Collection.Contains(value))
_Collection.Add(value);
}
}
public var GetProductInfos()
{
var productInfos =
from p in products
select new { p.ProductName, p.Category, Price = p.UnitPrice };
return productInfos;
}
foreach (Control c in f.Controls)
{
//希望有隐式转换
IReadOnlyRestrictable if interface contract is in class we are checking against
IReadOnlyRestricable editable = c as IReadOnlyRestricable;
if (editable != null)
editable.ReadOnly = true;
}
在我看来ducktyping的最大好处是可以为你不需要访问的类库定义一些接口,这可以尽可能地减少相互依赖,你可以查看Phil Haacks more extensive post on duck typing这文章来看看为什么作者相信这对C#有好处。
Krzysztof Cwalina认为,很显然的,C#的foreach关键字已经使用了duck typing.