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> /// 得到指定的 ...
随机推荐
- spring boot 自动生成mybatis代码
1)在pom.xml中增加generator插件 <!--自动生成mybaits--> <plugin> <groupId>org.mybatis.generato ...
- mongodb windows 开机启动
1)新建存放db E:\mongodb\data\db 2)新建日志文件 E:\mongodb\logs\log.txt 3)管理员运行Cmd 4)CD mongodb安装路径 5)运行命令 mong ...
- iOS之绘制像素到屏幕
译注:这篇文章虽然比较长,但是里面的内容还是很有价值的. 像素是如何绘制到屏幕上面的?把数据输出到屏幕的方法有很多,通过调用很多不同的framework和不同的函数.这里我们讲一下这个过程背后的东西. ...
- 洛谷——P4109 [HEOI2015]定价
P4109 [HEOI2015]定价 模拟(有点儿贪心) 题目要求在区间$l,r$中$x$后导0尽量多,且除去后导0之外,最后一个数尽量是$5$才最优 从$l$到$r$依次考虑, 假设当前考虑到$50 ...
- CF528D Fuzzy Search 字符串匹配+FFT
题意: DNA序列,在母串s中匹配模式串t,对于s中每个位置i,只要s[i-k]到s[i+k]中有c就认为匹配了c.求有多少个位置匹配了t. 分析: 这个字符串匹配的方式,什么kmp,各种自动机都不灵 ...
- P2756 网络流解决二分图最大匹配
P2756 飞行员配对方案问题 题目背景 第二次世界大战时期.. 题目描述 P2756 飞行员配对方案问题 英国皇家空军从沦陷国征募了大量外籍飞行员.由皇家空军派出的每一架飞机都需要配备在航行技能和语 ...
- my97datepicker插件日期值改变事件 等同于input的onchang()时间
官网Demo地址http://www.my97.net/demo/index.htm <input type="text" class="Wdate" v ...
- zzuli 1905 小火山的跳子游戏
Description 小火山和火山火山在一块玩跳子游戏.规则如下: 1:跳子的起始位置为0,棋盘大小从1到N 2:每次跳子跳k步. 例如当前位置为i, 那么下一步为i + k 3:跳 ...
- 【HIHOCODER 1043】题目1 : 完全背包
描述 且说之前的故事里,小Hi和小Ho费劲心思终于拿到了茫茫多的奖券!而现在,终于到了小Ho领取奖励的时刻了! 等等,这段故事为何似曾相识?这就要从平行宇宙理论说起了---总而言之,在另一个宇宙中,小 ...
- Sed命令基础操作
sed用法的小技巧 (1)在查找范围时不需要用到替换,所以不用s; (2)当只需要打印被修改行时,可以使用-n 和 –p 选项,注意二者一定配合使用: 3种方式指定命令行上的多重指令 (1)用逗号分隔 ...
复制代码