一、何为泛型
泛型是指通过参数化类型在同一份代码操作多种类型,简单来说泛型就像用户定义了一个模板,用户传入什么样的参数,这个模板就会输出什么的结果。
C#泛型和C++模板之间的区别:
1、C#泛型为提供与C++模板相同程度的灵活性。例如尽管在C#泛型类中可以调用用户定义的运算符,但不能调用算术符.
2、C#不允许非类型模板参数,例如template C<int c>{}
3、 C#不支持显示专用化,即特定类型的模板的自定实现。
4、C#不支持部分专用化,例如类型参数子集的自定义实现。
5、C#不允许将类型参数作为泛型类型的基类
6、C#不允许类型的参数的默认类型
7、在C#中,尽管构造类型可用做泛型,但是泛型类型参数自身不能是泛型。c++确实允许模板参数
8、C++允许并对模板中的所有类型参数都有效的代码,然后检查代码中是否有用作于类型参数的特定类型。C#要求相应的编写类中的代码。例如,可以在C++中编码对类型参数的对象使用算术运算符+和-的函数。
二、样例代码
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using myns = System.Math;
using System.Data;
using System.Collections;
namespace ConsoleApplication22
{
class student//学生类
{
int sno;//学号
string sname;//姓名
public student() { }//构造函数
public student(int no, string name)
{
sno = no;
sname = name;
}
public void disstudent()//输出学生对象
{
Console.WriteLine("{0} {1}", sno, sname);
}
}
class teacher
{
int tno;//教师编号
string tname;//教师名称
public teacher() { }//构造函数
public teacher(int no, string name)//有参构造函数
{
tno = no;
tname = name;
}
public void disteacher()//输出教师对象
{
Console.WriteLine("{0} {1}", tno, tname);
}
}
class Stack<T>//声明栈类型
{
int maxsize;//栈中元素的最大个数
T[] data;//存放栈中的T类型元素
int top;//栈顶指针
public Stack()//构造函数
{
maxsize = 10;
data = new T[maxsize];
top = -1;
}
public bool StackEmpty()//判断栈空的方法
{
return top == -1;
}
public bool Push(T e)//元素进栈的方法
{
if (top == maxsize - 1)//栈满返回false
return false;
top++;
data[top] = e;
return true;
}
public bool Pop(ref T e)//元素出栈的方法
{
if (top == -1)//栈空返回false
return false;
e = data[top];
top--;
return true;
}
}
class Program
{
static void Main(string[] args)
{
int e = 0;//定义整数栈
Stack<int> s1 = new Stack<int>();
s1.Push(1);//三个整数入栈
s1.Push(2);
s1.Push(3);
Console.WriteLine("整数出栈的次数");
while(!s1.StackEmpty())//栈不空是元素出栈
{
s1.Pop(ref e);
Console.WriteLine("{0}",e);
}
Console.WriteLine();
double d=0;
Stack<double>s2=new Stack<double>();//定义实数栈
s2.Push(2.5);//3个实数进栈
s2.Push(3.8);
s2.Push(5.9);
Console.WriteLine("实数出栈的次序");
while(!s2.StackEmpty())//栈不空时元素出栈
{
s2.Pop(ref d);
Console.Write("{0}",d);
}
Console.WriteLine();
student st=new student();
Stack<student>s3=new Stack<student>();//定义学生栈
s3.Push(new student(1,"student"));//3个学生入栈
s3.Push(new student(2,"student2"));
s3.Push(new student(3, "student3"));
Console.WriteLine("学生的出栈顺序");
while (!s3.StackEmpty())//栈不空时入栈
{
s3.Pop(ref st);
st.disstudent();
}
Console.WriteLine();
teacher te = new teacher();
Stack<teacher> s4 = new Stack<teacher>();//定义教师栈
s4.Push(new teacher(1, "teacher"));//3个教师入栈
s4.Push(new teacher(2, "teacher2"));
s4.Push(new teacher(3, "teacher3"));
Console.WriteLine("教师对象的出栈顺序为");
while (!s4.StackEmpty())//栈不空时元素入栈
{
s4.Pop(ref te);
te.disteacher();
}
Console.WriteLine();
Console.Read();
}
}
}