C#中泛型方法与泛型接口 C#泛型接口 List<IAll> arssr = new List<IAll>(); interface IPerson<T> c# List<接口>小技巧 泛型接口协变逆变的几个问题
http://blog.csdn.net/aladdinty/article/details/3486532
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace 泛型
- {
- class 泛型接口
- {
- public static void Main()
- {
- PersonManager man = new PersonManager();
- Person per = new Person();
- man.PrintYourName(per);
- Person p1 = new Person();
- p1.Name = "p1";
- Person p2 = new Person();
- p2.Name = "p2";
- man.SwapPerson<Person>(ref p1, ref p2);
- Console.WriteLine( "P1 is {0} , P2 is {1}" , p1.Name ,p2.Name);
- Console.ReadLine();
- }
- }
- //泛型接口
- interface IPerson<T>
- {
- void PrintYourName( T t);
- }
- class Person
- {
- public string Name = "aladdin";
- }
- class PersonManager : IPerson<Person>
- {
- #region IPerson<Person> 成员
- public void PrintYourName( Person t )
- {
- Console.WriteLine( "My Name Is {0}!" , t.Name );
- }
- #endregion
- //交换两个人,哈哈。。这世道。。
- //泛型方法T类型作用于参数和方法体内
- public void SwapPerson<T>( ref T p1 , ref T p2)
- {
- T temp = default(T) ;
- temp = p1;
- p1 = p2;
- p2 = temp;
- }
- }
- }
为泛型集合类或表示集合中项的泛型类定义接口通常很有用。对于泛型类,使用泛型接口十分可取,例如使用 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 errorinterface IFebruary<T> : IMonth<int> { } //No errorinterface 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 errorclass SampleClass2<T> : IBaseInterface2<T, string> { } //No error
对于泛型类、泛型结构或泛型接口中的方法,控制方法重载的规则相同。
c# List<接口>小技巧
不同的情况下需要返回不同类型的数据集合,特点是,这些类型都继承自同一个接口。

public interface IExample { string ID { get; set; } string Name { get; set; } } public class A : IExample { public string ID { get; set; } public string Name { get; set; } } public class B : IExample { public string ID { get; set; } public string Name { get; set; } } public class Test { //方法A public List<T> GetRefList<T>(string key) where T : IExample { if (key == "A") return new List<A>(); else if (key == "B") return new List<A>(); } //方法B public T[] GetRefList<T>(string key) where T : IExample { if (key == "A") return new A[10]; else if (key == "B") return new B[10]; } //方法C public IExample[] GetRefList(string key) { if (key == "A") return new A[10]; else if (key == "B") return new B[10]; else return null; } //方法D public List<IExample> GetRefList(string key) { if (key == "A") return new List<A>(); else if (key == "B") return new List<B>(); else return null; } }

其中,方法A、B、D编译都不能通过,只有方法C可以编译通过。
补充一种情况:

//方法E public IEnumerable<IExample> GetRefList(string key) { if (key == "A") return new List<A>(); else if (key == "B") return new B[10]; else return null; }

可以编译通过。这样的话,原来存在的问题基本可以解决。
这里的List<IParent>和List<SubChild>之间的相互转换涉及到泛型的协变和抗变。
.NET4.0对IEnumerable接口的修改?
2.0中的定义:
public interface IEnumerable<T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}4.0中的定义:
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator();
}可以看到4.0中增加了对协变的支持。
可以在两个版本试下, 下面的语句在2.0下会报错。
List<SubClass> subarr = new List<SubClass>();
IEnumerable<IParent> parentarr = subarr;
这里参考资料:http://www.cnblogs.com/tenghoo/archive/2012/12/04/interface_covariant_contravariant.html
泛型接口协变逆变的几个问题
假设:TSub是TParent的子类。
协变:如果一个泛型接口IFoo<T>,IFoo<TSub>可以转换为IFoo<TParent>的话,我们称这个过程为协变,IFoo支持对参数T的协变。
逆变:如果一个泛型接口IFoo<T>,IFoo<TParent>可以转换为IFoo<TSub>的话,我们称这个过程为逆变,IFoo支持对参数T的逆变。
2、为什么要有协变、逆变?
通常只有具备继承关系的对象才可以发生隐式类型转换,如Base b=new sub()。
协变和逆变可以使得更多的类型之间能够实现隐式类型转换、类型安全性有了保障。
3、为什么泛型接口要引入协变、逆变?
基于以上原因的同时、许多接口仅仅将类型参数用于参数或返回值。所以支持协变和逆变后泛型的使用上有了更大的灵活性
4、为什么支持协变的参数只能用于方法的返回值?支持逆变的参数只能用于方法参数?
“TParent不能安全转换成TSub”,是这两个问题的共同原因。
我们定义一个接口IFoo。
{
void Method1(T param);
T Method2();
}
我们看一下协变的过程:IFoo<TSub>转换成IFoo<TParent>。
Method1:将TSub替换成TParent,Method1显然存在 TParent到TSub的转换。
Method2:返回值类型从TSub换成了TParent,是类型安全的。
所以支持协变的参数只能用在方法的返回值中。
再看一下逆变的过程:IFoo<TParent>转换成IFoo<TSub>。
Method1:将TParent替换成TSub,Method1存在 TSub到TParent的转换,是类型安全的。
Method2:返回值类型从TParent换成了TSub,是不安全的。
所以支持逆变的参数只能用在方法的参数中。
5、泛型接口支持协变、逆变和不支持协变、逆变的对比?
这其实是对3个问题的补充。
定义一个接口IFoo,既不支持协变,也不支持逆变。
{
void Method1(T param);
T Method2();
}
实现接口IFoo

{
public void Method1(T param)
{
Console.WriteLine(default(T));
}
public T Method2()
{
return default(T);
}
}

定义一个接口IBar支持对参数T的协变
{
T Method();
}
实现接口IBar

{
public T Method()
{
return default(T);
}
}

定义一个接口IBaz支持对参数T的逆变
{
void Method(T param);
}
实现接口IBaz

{
public void Method(T param)
{
Console.WriteLine(param.ToString());
}
}

定义两个有继承关系的类型,IParent和SubClass。

{
void DoSomething();
}
public class SubClass : IParent
{
public void DoSomething()
{
Console.WriteLine("SubMethod");
}
}

按照协变的逻辑,分别来使用IFoo和IBar。

IFoo<SubClass> foo_sub = new FooClass<SubClass>();
IFoo<IParent> foo_parent = foo_sub;//编译错误
//IBar 支持对参数T的协变
IBar<SubClass> bar_sub = new BarClass<SubClass>();
IBar<IParent> bar_parent = bar_sub;

foo_parent = foo_sub 会提示编译时错误“无法将类型“IFoo<SubClass>”隐式转换为“IFoo<IParent>”。存在一个显式转换(是否缺少强制转换?)”

IFoo<IParent> foo_parent = null;
IFoo<SubClass> foo_sub = foo_parent;//编译错误
//IBaz 对参数T逆变相容
IBaz<IParent> baz_parent = null;
IBaz<SubClass> baz_sub = baz_parent;

foo_sub = foo_parent 会提示编译时错误“无法将类型“IFoo<IParent>”隐式转换为“IFoo<ISub>”。存在一个显式转换(是否缺少强制转换?)”
6、.NET4.0对IEnumerable接口的修改?
2.0中的定义:
{
IEnumerator<T> GetEnumerator();
}
4.0中的定义:
{
IEnumerator<T> GetEnumerator();
}
可以看到4.0中增加了对协变的支持。
可以在两个版本试下, 下面的语句在2.0下会报错。
IEnumerable<IParent> parentarr = subarr;
参考:
http://www.cnblogs.com/Ninputer/archive/2008/11/22/generic_covariant.html
http://www.cnblogs.com/idior/archive/2010/06/20/1761383.html
http://www.cnblogs.com/artech/archive/2011/01/13/variance.html
C#中泛型方法与泛型接口 C#泛型接口 List<IAll> arssr = new List<IAll>(); interface IPerson<T> c# List<接口>小技巧 泛型接口协变逆变的几个问题的更多相关文章
- C#核心语法讲解-泛型(详细讲解泛型方法、泛型类、泛型接口、泛型约束,了解协变逆变)
泛型(generic)是C#语言2.0和通用语言运行时(CLR)的一个新特性.泛型为.NET框架引入了类型参数(type parameters)的概念.类型参数使得设计类和方法时,不必确定一个或多个具 ...
- C#核心语法-泛型(详细讲解泛型方法、泛型类、泛型接口、泛型约束,了解协变逆变)
泛型(generic)是C#语言2.0和通用语言运行时(CLR)的一个新特性.泛型为.NET框架引入了类型参数(type parameters)的概念.类型参数使得设计类和方法时,不必确定一个或多个具 ...
- 在net中json序列化与反序列化 面向对象六大原则 (第一篇) 一步一步带你了解linq to Object 10分钟浅谈泛型协变与逆变
在net中json序列化与反序列化 准备好饮料,我们一起来玩玩JSON,什么是Json:一种数据表示形式,JSON:JavaScript Object Notation对象表示法 Json语法规则 ...
- .NET 4.0中的泛型的协变和逆变
转自:http://www.cnblogs.com/jingzhongliumei/archive/2012/07/02/2573149.html 先做点准备工作,定义两个类:Animal类和其子类D ...
- 转载.NET 4.0中的泛型的协变和逆变
先做点准备工作,定义两个类:Animal类和其子类Dog类,一个泛型接口IMyInterface<T>, 他们的定义如下: public class Animal { } public ...
- .Net中委托的协变和逆变详解
关于协变和逆变要从面向对象继承说起.继承关系是指子类和父类之间的关系:子类从父类继承所以子类的实例也就是父类的实例.比如说Animal是父类,Dog是从Animal继承的子类:如果一个对象的类型是Do ...
- C#4.0中的协变和逆变
原文地址 谈谈.Net中的协变和逆变 关于协变和逆变要从面向对象继承说起.继承关系是指子类和父类之间的关系:子类从父类继承所以子类的实例也就是父类的实例.比如说Animal是父类,Dog是从Anima ...
- Scala中的协变,逆变,上界,下界等
Scala中的协变,逆变,上界,下界等 目录 [−] Java中的协变和逆变 Scala的协变 Scala的逆变 下界lower bounds 上界upper bounds 综合协变,逆变,上界,下界 ...
- c#打包文件解压缩 C#中使用委托、接口、匿名方法、泛型委托实现加减乘除算法 一个简单例子理解C#的协变和逆变 对于过长字符串的大小比对
首先要引用一下类库:using Ionic.Zip;这个类库可以到网上下载. 下面对类库使用的封装方法: 得到指定的输入流的ZIP压缩流对象 /// <summary> /// 得到指定的 ...
随机推荐
- 模拟--P1540 机器翻译
题目连接 题目背景 小晨的电脑上安装了一个机器翻译软件,他经常用这个软件来翻译英语文章. 题目描述 这个翻译软件的原理很简单,它只是从头到尾,依次将每个英文单词用对应的中文含义来替换.对于每个英文单词 ...
- (6) openssl passwd(生成加密的密码)
该伪命令用于生成加密的密码 [root@docker121 ssl]# man -f passwd passwd (1) - update user's authentication tokens p ...
- python-基本运算符(解压缩-必考)
基本运算符 算术运算符 x =10 y =20 print(x+y) 30 print(x-y) -10 print(x*y) 200 print(x/y) 0.5 print(x%y)#取余 10 ...
- EmpireofCode文档翻译 https://empireofcode.com/game/
In Campaign mode, you can check your strategies on already defeated bases. You will not lose your tr ...
- Eclipse设置反编译插件
有些项目我们想看看引入的包的源码的时候,因为打包好的.class文件的内容我们是看不懂的,但是又懒得去找源码文件的时候,就会用到反编译工具. 步骤: 1.安装反编译插件. 2.设置使用的反编译工具. ...
- C#sql语句如何使用占位符
背景:在程序中,写sql语句时,可能要根据变量的值不同,SQL语句产生相应的变化.比如说存在变量StuName,根据变量值的不同,检索不同姓名的学生记录,这时需用到占位符的知识. 1,{0}占位符,代 ...
- Golang 编写 Tcp 服务器
Golang 作为广泛用于服务端和云计算领域的编程语言,tcp socket 是其中至关重要的功能.无论是 WEB 服务器还是各类中间件都离不开 tcp socket 的支持. Echo 服务器 拆包 ...
- Spring☞WebApplicationContext的继承关系
spring mvc里的root/child WebApplicationContext的继承关系 在传统的spring mvc程序里会有两个WebApplicationContext,一个是pare ...
- SqlParameter[] parameters
SqlParameter[] parameters = { new SqlParameter("@rdTypeName", readertype.rdTypeName), new ...
- Nginx与python web服务配置(Uwsgi& FastCGI)
Uwsgi start uswgi uwsgi --harakiri 360000 --body-read-warning=10000 --max-fd=65536 -b 1000000 --http ...