您的位置:首页 > Web前端

Effective C# 学习笔记(二十二)多用接口定义实现,少用继承

2011-07-13 16:08 232 查看
首先从宏观上区分接口和类型

接口定义了行为

类型定义特性及继承结构,即是实体间的关系

接口和抽象类的区分

接口和抽象类都可定义行为而不实现 ,但抽象类可以

接口可以被多继承(实现),抽象类只可被继承一个

技巧

利用扩展方法来为接口添加统一实现方法。

例如.net framework 中的System.Linq.Enumerable<T>为IEnumerable<T>接口实现了30多个扩展方法,示例代码如下:

public static class Extensions

{

public static void ForAll<T>(

this IEnumerable<T> sequence,

Action<T> action)

{

foreach (T item in sequence)

action(item);

}

}

// usage

foo.ForAll((n) => Console.WriteLine(n.ToString()));

利用接口作为参数和返回值的类型

例如:

public static void PrintCollection<T>(IEnumerable<T> collection)

{

foreach (T o in collection)

Console.WriteLine("Collection contains {0}",o.ToString());

}

对类的消费者只暴露部分类实现的接口,可以保证你的类得到最大限度的保护

利用接口,扩展struct类型的行为,例如可以让结构体实现IComparable和Icomparable<T>接口,来为SortedList<T>类型的结构体集合提供比较大小的行为特性

代码如下:

public struct URLInfo : IComparable<URLInfo>, IComparable

{

private string URL;

private string description;

#region IComparable<URLInfo> Members

public int CompareTo(URLInfo other)

{

return URL.CompareTo(other.URL);

}

#endregion

#region IComparable Members

int IComparable.CompareTo(object obj)

{

if (obj is URLInfo)

{

URLInfo other = (URLInfo)obj;

return CompareTo(other);

}

else

throw new ArgumentException(

"Compared object is not URLInfo");

}

#endregion

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐