学习C#泛型概述,泛型类的一些说明
程序员文章站
2022-03-01 17:46:44
...
泛型类是定义了一个模板,在实例化时,编译器将为它生成了一个全新的类,例如,
//值类型
Queue<int> intQueue = new Queue<int>();
//引用类型
Queue<Person> personQueue = new Queue<Person>();
这里是有两个类,称为已构造类型(constructed type)。
要确保泛型类使用的类型参数是提供了特定方法的类型,可用约束来规定这一条件,例如
定义接口IPrintable,具有打印功能
//可打印接口
interface IPrintable
{
void IPrint();
}
为Person类实现接口
class Person : IPrintable
{
private String name;
public Person()
{
name = null;
}
public Person(String personname)
{
name = personname;
}
public void IPrint()
{
Console.WriteLine($"person name is {this.name}");
}
}
这是,约束queue的成员是有打印功能的类的方法可写出:
//一个先进先出的队列
class Queue<T> where T: IPrintable
这时int类型就不能实现queue了
上一篇: 求小于等于n的质数个数
下一篇: 经典算法(1)- 求1到N的质数