为泛型集合类或表示集合中项的泛型类定义接口通常很有用。对于泛型类,使用泛型接口十分可取,例如使用 IComparable<T> 而不使用 IComparable,这样可以避免值类型的装箱和取消装箱操作。.NET Framework 2.0 类库定义了若干新的泛型接口,以用于 System.Collections.Generic 命名空间中新的集合类。

将接口指定为类型参数的约束时,只能使用实现此接口的类型。下面的代码示例显示从 GenericList<T> 类派生的 SortedList<T> 类。SortedList<T> 添加了约束 where T : IComparable<T>。这将使SortedList<T> 中的 BubbleSort 方法能够对列表元素使用泛型 CompareTo 方法。在此示例中,列表元素为简单类,即实现 IComparable<Person> 的 Person

C#
//Type parameter T in angle brackets.
public class GenericList<T> : System.Collections.Generic.IEnumerable<T>
{
protected Node head;
protected Node current = null; // Nested class is also generic on T
protected class Node
{
public Node next;
private T data; //T as private member datatype public Node(T t) //T used in non-generic constructor
{
next = null;
data = t;
} public Node Next
{
get { return next; }
set { next = value; }
} public T Data //T as return type of property
{
get { return data; }
set { data = value; }
}
} public GenericList() //constructor
{
head = null;
} public void AddHead(T t) //T as method parameter type
{
Node n = new Node(t);
n.Next = head;
head = n;
} // Implementation of the iterator
public System.Collections.Generic.IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
} // IEnumerable<T> inherits from IEnumerable, therefore this class
// must implement both the generic and non-generic versions of
// GetEnumerator. In most cases, the non-generic method can
// simply call the generic method.
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
} public class SortedList<T> : GenericList<T> where T : System.IComparable<T>
{
// A simple, unoptimized sort algorithm that
// orders list elements from lowest to highest: public void BubbleSort()
{
if (null == head || null == head.Next)
{
return;
}
bool swapped; do
{
Node previous = null;
Node current = head;
swapped = false; while (current.next != null)
{
// Because we need to call this method, the SortedList
// class is constrained on IEnumerable<T>
if (current.Data.CompareTo(current.next.Data) > 0)
{
Node tmp = current.next;
current.next = current.next.next;
tmp.next = current; if (previous == null)
{
head = tmp;
}
else
{
previous.next = tmp;
}
previous = tmp;
swapped = true;
}
else
{
previous = current;
current = current.next;
}
}
} while (swapped);
}
} // A simple class that implements IComparable<T> using itself as the
// type argument. This is a common design pattern in objects that
// are stored in generic lists.
public class Person : System.IComparable<Person>
{
string name;
int age; public Person(string s, int i)
{
name = s;
age = i;
} // This will cause list elements to be sorted on age values.
public int CompareTo(Person p)
{
return age - p.age;
} public override string ToString()
{
return name + ":" + age;
} // Must implement Equals.
public bool Equals(Person p)
{
return (this.age == p.age);
}
} class Program
{
static void Main()
{
//Declare and instantiate a new generic SortedList class.
//Person is the type argument.
SortedList<Person> list = new SortedList<Person>(); //Create name and age values to initialize Person objects.
string[] names = new string[]
{
"Franscoise",
"Bill",
"Li",
"Sandra",
"Gunnar",
"Alok",
"Hiroyuki",
"Maria",
"Alessandro",
"Raul"
}; int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 }; //Populate the list.
for (int x = 0; x < 10; x++)
{
list.AddHead(new Person(names[x], ages[x]));
} //Print out unsorted list.
foreach (Person p in list)
{
System.Console.WriteLine(p.ToString());
}
System.Console.WriteLine("Done with unsorted list"); //Sort the list.
list.BubbleSort(); //Print out sorted list.
foreach (Person p in list)
{
System.Console.WriteLine(p.ToString());
}
System.Console.WriteLine("Done with sorted list");
}
}

可将多重接口指定为单个类型上的约束,如下所示:

C#
class Stack<T> where T : System.IComparable<T>, IEnumerable<T>
{
}

一个接口可定义多个类型参数,如下所示:

interface IDictionary<K, V>
{
}

类之间的继承规则同样适用于接口:

C#
interface IMonth<T> { }

interface IJanuary : IMonth<int> { } //No error
interface IFebruary<T> : IMonth<int> { } //No error
interface IMarch<T> : IMonth<T> { } //No error
//interface IApril<T> : IMonth<T, U> {} //Error

如果泛型接口为逆变的,即仅使用其类型参数作为返回值,则此泛型接口可以从非泛型接口继承。在 .NET Framework 类库中,IEnumerable<T> 从 IEnumerable 继承,因为 IEnumerable<T> 仅在 GetEnumerator 的返回值和当前属性 getter 中使用 T。

具体类可以实现已关闭的构造接口,如下所示:

C#
interface IBaseInterface<T> { }

class SampleClass : IBaseInterface<string> { }

只要类参数列表提供了接口必需的所有参数,泛型类便可以实现泛型接口或已关闭的构造接口,如下所示:

C#
interface IBaseInterface1<T> { }
interface IBaseInterface2<T, U> { } class SampleClass1<T> : IBaseInterface1<T> { } //No error
class SampleClass2<T> : IBaseInterface2<T, string> { } //No error

对于泛型类、泛型结构或泛型接口中的方法,控制方法重载的规则相同。

C#泛型接口的更多相关文章

  1. 让我们用心感受泛型接口的协变和抗变out和in

    关键字out和in相信大家都不陌生,系统定义的很多泛型类型大家F12都或多或少看见了.但是实际中又很少会用到,以前在红皮书里看到,两三页就介绍完了.有的概念感觉直接搬出来的,只是说这样写会怎样,并没有 ...

  2. typealias和泛型接口

    typealias 是用来为已经存在的类型重新定义名字的,通过命名,可以使代码变得更加清晰.使用的语法也很简单,使用 typealias 关键字像使用普通的赋值语句一样,可以将某个已经存在的类型赋值为 ...

  3. Java泛型学习笔记 - (五)泛型接口

    所谓泛型接口, 类似于泛型类, 就是将泛型定义在接口上, 其格式如下: public interface 接口名<类型参数>如: interface Inter<T> { pu ...

  4. Swift开发第九篇——Any和AnyObject&typealias和泛型接口

    本篇分为两部分: 一.Swift中的Any和AnyObject 二.Swift中的typealias和泛型接口 一.Swift中的Any和AnyObject 在 Swift 中,AnyObject 可 ...

  5. java 泛型 -- 泛型类,泛型接口,泛型方法

    泛型T泛型的许多最佳例子都来自集合框架,因为泛型让您在保存在集合中的元素上指定类型约束.在定义泛型类或声明泛型类的变量时,使用尖括号来指定形式类型参数.形式类型参数与实际类型参数之间的关系类似于形式方 ...

  6. java 泛型接口示例

    /* * 泛型接口 */ interface Tool<t> { public void show(T t); //泛型方法 public <e> void print(E e ...

  7. java 16 -7 泛型方法和泛型接口(泛型类相似)

    写一个ObjectTool类 泛型方法:把泛型定义在方法上 格式 public <泛型类型> 返回类型 方法名(泛型类型) 这样的好处是: 这个泛型方法可以接收任意类型的数据 public ...

  8. 解决WebService 中泛型接口不能序列化问题

    本来要定义WebServices 方法返回一泛型接口集合IList,系统提示不能序列化泛型接口集合  1   [WebMethod]  2         public IList<Employ ...

  9. Android(java)学习笔记91:泛型接口的概述和使用

    package cn.itcast_06; /* * 泛型接口:把泛型定义在接口上 */ public interface Inter<T> { public abstract void ...

随机推荐

  1. C#中Application.DoEvents()的作用

    Visual Studio里的摘要:处理当前在消息队列中的所有 Windows 消息. 交出CPU控制权,让系统可以处理队列中的所有Windows消息,比如在大运算量循环内,加Application. ...

  2. FormsAuthentication.HashPasswordForStoringInConfigFile 方法 之研究

    摘自:http://time-is-life.cnblogs.com/articles/322523.html 给定标识哈希类型的密码和字符串,该例程产生一个适合存储在配置文件中的哈希密码. [C#] ...

  3. poj1755Triathlon(半平面交)

    链接 根据题意可以设三段路程分别为A,B,C 那么总时间t = A/V+B/U+C/W. 这样根据时间大小关系可以跟其余n-1个联立形成n-1个方程. 化简后为A(1/vj-1/vi)+B(1/uj- ...

  4. 64位WIN7+oracle11g+plsql安装

    64位WIN7+oracle11g+plsql安装   上部转自Oracle 11g R2 for Win7旗舰版(64位)的安装步骤 1.下载Oracle 11g R2 for Windows的版本 ...

  5. Python学习(22)python网络编程

    Python 网络编程 Python 提供了两个级别访问的网络服务.: 低级别的网络服务支持基本的 Socket,它提供了标准的 BSD Sockets API,可以访问底层操作系统Socket接口的 ...

  6. Python学习笔记2—内置函数

    函数的使用 官方文档:https://docs.python.org/2/library/functions.html

  7. ListFragment

    ListFragment http://developer.android.com/reference/android/app/ListFragment.html extends Fragment C ...

  8. eclipse+adt+sdk开发环境搭配

    1.开发环境配置 http://www.mamicode.com/info-detail-516839.html

  9. table合并单元格colspan和rowspan .

    colspan和rowspan这两个属性用于创建特殊的表格. colspan是“column span(跨列)”的缩写.colspan属性用在td标签中,用来指定单元格横向跨越的列数: 在浏览器中将显 ...

  10. package-info.java文件详解

    欢迎关注我的社交账号: 博客园地址: http://www.cnblogs.com/jiangxinnju/p/4781259.html GitHub地址: https://github.com/ji ...