泛型接口

1,使用泛型接口的好处:

  1)提供出色的编译时类型安全;有的接口(比喻非泛型接口 ICompareable)定义的方法有object参数或返回类型,当代码调用这些接口方法时,可以传递对任何对象的引用,但这不是我们期望的;

 

 1private void SomeMethod1() 
 2{
 3Int32 x = 1, y = 2;
 4IComparable c = x;
 5// CompareTo expects an Object; passing y (an Int32) is OK
 6c.CompareTo(y); // Boxing occurs here
 7// CompareTo expects an Object; passing "2" (a String) compiles
 8// but an ArgumentException is thrown at runtime
 9c.CompareTo("2");
10}

   显然,理想的是让接口方法接受强类型,基于这个原因,FCL 中包含一个泛型接口IComparable<T>.

  

Code

   2) 操作值类型,不需要太多的装箱;

   3)类可以实现同一个接口若干次,只要使用不同的类型参数。

 

 1using System;
 2// This class implements the generic IComparable<T> interface twice
 3public sealed class Number: IComparable<Int32>, IComparable<String> 
 4{
 5   private Int32 m_val = 5;
 6   // This method implements IComparable<Int32>'s CompareTo
 7   public Int32 CompareTo(Int32 n) {
 8   return m_val.CompareTo(n);
 9}

10// This method implements IComparable<String>'s CompareTo
11public Int32 CompareTo(String s) 
12  {
13   return m_val.CompareTo(Int32.Parse(s));
14  }

15}

16public static class Program 
17{
18   public static void Main() 
19  {
20     Number n = new Number();
21     // Here, I compare the value in n with an Int32 (5)
22     IComparable<Int32> cInt32 = n;
23    Int32 result = cInt32.CompareTo(5);
24    // Here, I compare the value in n with a String ("5")
25    IComparable<String> cString = n;
26   result = cString.CompareTo("5");
27   }

28}

 

posted @ 2009-02-25 12:52  路飞船长  Views(960)  Comments(0Edit  收藏  举报