1,使用泛型接口的好处:
1)提供出色的编译时类型安全;有的接口(比喻非泛型接口 ICompareable)定义的方法有object参数或返回类型,当代码调用这些接口方法时,可以传递对任何对象的引用,但这不是我们期望的;
1
private void SomeMethod1()
2
{
3
Int32 x = 1, y = 2;
4
IComparable c = x;
5
// CompareTo expects an Object; passing y (an Int32) is OK
6
c.CompareTo(y); // Boxing occurs here
7
// CompareTo expects an Object; passing "2" (a String) compiles
8
// but an ArgumentException is thrown at runtime
9
c.CompareTo("2");
10
}

2

3

4

5

6

7

8

9

10

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

2) 操作值类型,不需要太多的装箱;
3)类可以实现同一个接口若干次,只要使用不同的类型参数。
1
using System;
2
// This class implements the generic IComparable<T> interface twice
3
public 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
11
public Int32 CompareTo(String s)
12
{
13
return m_val.CompareTo(Int32.Parse(s));
14
}
15
}
16
public 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
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28
