通用接口(C#编程指南) [英] Generic Interfaces (C# Programming Guide)
问题描述
你好
我正在浏览通用接口(C#编程指南)上的主题,该主题的链接为
I was going through the topic on Generic Interfaces (C# Programming Guide) whose link is
http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx 我遇到了语句"
http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx I came across the statement "When an interface is specified as a constraint on a type parameter, only types that implement the interface can be used" . I tried to understand but could not. Please help. The code as below.
致谢
Manoj Gokhale
Manoj Gokhale
// Statement => When an interface is specified as a constraint
// on a type parameter, only types that implement
// the interface can be used
namespace ConsoleApplication1
{
public interface I1<T>
{
void m1(int aa);
}
// interface is specified as a constraint
// on a type parameter
public class genclass<T> where T : I1<T>
{
public void m1(int x){}
public void m2(){}
}
// genclass1<T> does implement the interface I1<T>
public class genclass1<T> : I1<T>
{
public void m1(int yy){}
public void m3(){}
}
// class2<T> does not implement the interface I1<T>
public class class2<T>
{
public void m4(){}
}
class TestGenericList
{
static void Main()
{
genclass1<int> xx = new genclass1<int>();
// No compile error
xx.m3();
class2<int> yy = new class2<int>();
yy.m4();
}
}
}
推荐答案
我认为此评论引用的是以下课程
I think the comment is refereing to the following class
公共类Person:System.IComparable< Person>
public class Person : System.IComparable<Person>
您只能在"Person"上对以上课程进行排序
The above class your can only sort on 'Person'
普通班使用此类
公共类SortedList< T> :GenericList< T>其中T:System.IComparable< T>
public class SortedList<T> : GenericList<T> where T : System.IComparable<T>
上面的类将对任何类型的System.IComparable< T>
The above class will sort on any type of System.IComparable<T>
这篇关于通用接口(C#编程指南)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!