代码改变世界

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

2011-07-13 16:08  小郝(Kaibo Hao)  阅读(313)  评论(0编辑  收藏  举报

首先从宏观上区分接口和类型

  1. 接口定义了行为
  2. 类型定义特性及继承结构,即是实体间的关系

 

接口和抽象类的区分

  1. 接口和抽象类都可定义行为而不实现 ,但抽象类可以
  2. 接口可以被多继承(实现),抽象类只可被继承一个

 

技巧

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

例如.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()));

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

例如:

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

{

foreach (T o in collection)

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

}

  1. 对类的消费者只暴露部分类实现的接口,可以保证你的类得到最大限度的保护
  2. 利用接口,扩展struct类型的行为,例如可以让结构体实现IComparableIcomparable<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

}