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 ...
随机推荐
- 一张png图片 上面有多个图标,如何用CSS准确的知道其中某个图片的坐标
一张png图片 上面有多个图标,如何用CSS准确的知道其中某个图片的坐标 ,如下图 可以使用 background background:url(images/xx.png) 40px 10px n ...
- iOS - Swift iOS 开发体系
1.iOS 开发技术体系 iOS 开发技术体系图: 层级 主要框架 Cocoa Touch UIKit 等 Media Core Graphics .OpenGl ES.Core Animation ...
- Spring事务配置
Spring中事务的配置学习: 1.心法 Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource.TransactionManager和代理机制这三部分,无论哪种配置方式,一 ...
- HTTP refere
什么是 http refere ? 简言之,放在web浏览器的header上的 当我通过我的主页访问我朋友的网站时,就可以获得refere , 可以获取网页访问流量,也可以防盗链 一般 referer ...
- 刻录DVD_目录
1.down.52pojie.cn (20160701) (1 in 5) 工具 2.down.52pojie.cn (20160701) (2 in 5) Android VM 6/7 3.down ...
- LCD控制器与驱动器
这回我再讲讲从 MCU 到 LCD 之间是怎样一个控制流程,即我们的位图数据是怎样显示到 LCD 上的.前面我们了解到 LCD 显示是用动态扫描的方式来实现的,每次显示一整行,在一帧里每行一次扫描一遍 ...
- mysql 编码测试
insert into t1(v1) values('cn中国'); select * from t1; 1.输入gbk,交互latin1,数据库latin1 insert,客户端把gbk的输入当成l ...
- 使用连接来代替in和not in(使用外连接技巧)
比如:表A里面的一个字段叫做MOBILE 里面存的记录如下 : 123456781 表B里面的一个字段也叫做MOBILE里面存的记录如下 12341910 (1)我们要查询一下A和B里面都有的,以 ...
- typeof升级版,可以识别出array、object、null、nan、[]、{}
typeof 经常混淆array.object.null等,升级处理一下. 可以将这个函数放在common.js中使用. function getTypeName(v) { var v_str = J ...
- ViewPager 基本方式加载view
1.新建view_pager.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayo ...