C#泛型接口
为泛型集合类或表示集合中项的泛型类定义接口通常很有用。对于泛型类,使用泛型接口十分可取,例如使用 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。
//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");
}
}
可将多重接口指定为单个类型上的约束,如下所示:
class Stack<T> where T : System.IComparable<T>, IEnumerable<T>
{
}
一个接口可定义多个类型参数,如下所示:
interface IDictionary<K, V>
{
}
类之间的继承规则同样适用于接口:
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。
具体类可以实现已关闭的构造接口,如下所示:
interface IBaseInterface<T> { }
class SampleClass : IBaseInterface<string> { }
只要类参数列表提供了接口必需的所有参数,泛型类便可以实现泛型接口或已关闭的构造接口,如下所示:
interface IBaseInterface1<T> { }
interface IBaseInterface2<T, U> { }
class SampleClass1<T> : IBaseInterface1<T> { } //No error
class SampleClass2<T> : IBaseInterface2<T, string> { } //No error
对于泛型类、泛型结构或泛型接口中的方法,控制方法重载的规则相同。
C#泛型接口的更多相关文章
- 让我们用心感受泛型接口的协变和抗变out和in
关键字out和in相信大家都不陌生,系统定义的很多泛型类型大家F12都或多或少看见了.但是实际中又很少会用到,以前在红皮书里看到,两三页就介绍完了.有的概念感觉直接搬出来的,只是说这样写会怎样,并没有 ...
- typealias和泛型接口
typealias 是用来为已经存在的类型重新定义名字的,通过命名,可以使代码变得更加清晰.使用的语法也很简单,使用 typealias 关键字像使用普通的赋值语句一样,可以将某个已经存在的类型赋值为 ...
- Java泛型学习笔记 - (五)泛型接口
所谓泛型接口, 类似于泛型类, 就是将泛型定义在接口上, 其格式如下: public interface 接口名<类型参数>如: interface Inter<T> { pu ...
- Swift开发第九篇——Any和AnyObject&typealias和泛型接口
本篇分为两部分: 一.Swift中的Any和AnyObject 二.Swift中的typealias和泛型接口 一.Swift中的Any和AnyObject 在 Swift 中,AnyObject 可 ...
- java 泛型 -- 泛型类,泛型接口,泛型方法
泛型T泛型的许多最佳例子都来自集合框架,因为泛型让您在保存在集合中的元素上指定类型约束.在定义泛型类或声明泛型类的变量时,使用尖括号来指定形式类型参数.形式类型参数与实际类型参数之间的关系类似于形式方 ...
- java 泛型接口示例
/* * 泛型接口 */ interface Tool<t> { public void show(T t); //泛型方法 public <e> void print(E e ...
- java 16 -7 泛型方法和泛型接口(泛型类相似)
写一个ObjectTool类 泛型方法:把泛型定义在方法上 格式 public <泛型类型> 返回类型 方法名(泛型类型) 这样的好处是: 这个泛型方法可以接收任意类型的数据 public ...
- 解决WebService 中泛型接口不能序列化问题
本来要定义WebServices 方法返回一泛型接口集合IList,系统提示不能序列化泛型接口集合 1 [WebMethod] 2 public IList<Employ ...
- Android(java)学习笔记91:泛型接口的概述和使用
package cn.itcast_06; /* * 泛型接口:把泛型定义在接口上 */ public interface Inter<T> { public abstract void ...
随机推荐
- netty概念
Netty的ChannelFuture在Netty中的所有的I/O操作都是异步执行的,这就意味着任何一个I/O操作会立刻返回,不保证在调用结束的时候操作会执行完成.因此,会返回一个ChannelFut ...
- poj2420A Star not a Tree?(模拟退火)
链接 求某一点到其它点距离和最小,求这个和,这个点 为费马点. 做法:模拟退火 #include <iostream> #include<cstdio> #include< ...
- 把excel中的数据导入到数据库
import.php <?php header("Content-Type:text/html;charset=utf-8"); echo '<html> < ...
- Java数组实现五子棋功能
package ch4; import java.io.*; /** * Created by Jiqing on 2016/11/9. */ public class Gobang { // 定义棋 ...
- Hadoop与Spark比较
先看这篇文章:http://www.huochai.mobi/p/d/3967708/?share_tid=86bc0ba46c64&fmid=0 直接比较Hadoop和Spark有难度,因为 ...
- DOS中文乱码解决
在中文Windows系统中,如果一个文本文件是UTF-8编码的,那么在CMD.exe命令行窗口(所谓的DOS窗口)中不能正确显示文件中的内容.在默认情况下,命令行窗口中使用的代码页是中文或者美国的,即 ...
- C# winform解决解决窗体第一次设置为最大化后,点击最大化按钮窗体无法居中问题
public frmMain() { InitializeComponent(); //解决窗体第一次设置为最大化后,点击最大化按钮窗体无法居中问题 int x = Convert.ToInt32(( ...
- 使用Mozilla Firefox插件RestClient测试Http API接口
RESTClient是Mozilla Firefox一个用于测试http请求插件.在火狐附加组件里面查询并安装,非常小巧,界面非常简单,使用非常的方便,看下面这张图你就全明白了,希望对新手有帮助! 1 ...
- Nginx安装(zhuan)
http://www.nginx.cn/install ************************ nginx可以使用各平台的默认包来安装,本文是介绍使用源码编译安装,包括具体的编译参数信息. ...
- 项目中的五级地址联动效果(js)
我刚开始是的时候是是写了一个sql语句,但是写了5个函数,来联动地址的.后来请教了前段的师傅,用js来写了一个地址联动的. 我使用的是easyui的框架! 地址联动部分html代码! <tr&g ...
复制代码