通用栈类
1.object数组
数值类型转化成object类型需要装箱、拆箱
所有类型均可放入
但是大多数情况下,需要合理数据类型,不是所有类型,所以有这个问题
时间效率低
2.C#提供的泛型
T可以换成各种类型,将被具体类型所取代
效率高,不需要拆箱、装箱过程,创造后可以进行类型检查
栈、线性表、队列等的全部由.net提供了,System.Collections是object实现的
System.Collection.Generic是支持泛型实现的
------------泛型约束-------------------------满足一定条件后,才可以替换
eg:条件
解决初始化问题:提供了Default关键字
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{//throw和finally
static void Main(string[] args)
{
int[] intA = { 1,2,3};
double[] dbB = { 1.1, 2.2, 3.3 };
char[] chC = { 'a', 'b', 'c' };
Display(intA);
Display(dbB);
Display(chC);
}
static void Display<T>(T[] a)
{
foreach (T k in a)
{
Console.Write("k={0} ",k);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{//throw和finally
static void Main(string[] args)
{
int[] intA = { 1,2,3};
double[] dbB = { 1.1, 2.2, 3.3 };
char[] chC = { 'a', 'b', 'c' };
//Display(intA);
//Display(dbB);
//Display(chC);
Stack<int> s = new Stack<int>(10);
s.Bottom = 0;
for (int i = 0; i < s.element.Length; i++)
{
s.element[i] = i;
s.Top++;
}
Display(s.element);
}
static void Display<T>(T[] a)
{
foreach (T k in a)
{
Console.Write("k={0} ",k);
}
}
}
class Stack<Ttype>
{
private int top;
private int bottom;
public Ttype[] element;
public int Top
{
get
{
return top;
}
set
{
top = value;
}
}
public int Bottom
{
get
{
return bottom;
}
set
{
bottom = value;
}
}
public Stack(int size)
{
element = new Ttype[size];
}
}
}
object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{//throw和finally
static void Main(string[] args)
{
int[] intA = { 1,2,3};
double[] dbB = { 1.1, 2.2, 3.3 };
char[] chC = { 'a', 'b', 'c' };
//Display(intA);
//Display(dbB);
//Display(chC);
Stack<int> s = new Stack<int>(10);
s.Bottom = 0;
for (int i = 0; i < s.element.Length; i++)
{
s.element[i] = i;
s.Top++;
}
Display(s.element);
Console.WriteLine();
System.Collections.Stack s1 = new System.Collections.Stack(12);
for (int i = 0; i<intA.Length; i++)
{
s1.Push(intA[i]);
}
for (int i = 0; i < dbB.Length; i++)
{
s1.Push(dbB[i]);
}
for (int i = 0; i < chC.Length; i++)
{
s1.Push(chC[i]);
}
for (int i = 0; i < intA.Length+dbB.Length+chC.Length; i++)
{
Console.WriteLine(s1.Pop());
}
}
static void Display<T>(T[] a)
{
foreach (T k in a)
{
Console.Write("k={0} ",k);
}
}
}
class Stack<Ttype>
{
private int top;
private int bottom;
public Ttype[] element;
public int Top
{
get
{
return top;
}
set
{
top = value;
}
}
public int Bottom
{
get
{
return bottom;
}
set
{
bottom = value;
}
}
public Stack(int size)
{
element = new Ttype[size];
}
}
}