现在的位置: 首页 > 综合 > 正文

C#.NET中的泛型(带参数的类)在栈中的运用

2012年08月18日 ⁄ 综合 ⁄ 共 1154字 ⁄ 字号 评论关闭

/*
 * Created by SharpDevelop.
 * User: noo
 * Date: 2009-8-15
 * Time: 15:57
 * 
 * 泛型在栈中的运用
 
*/
using System ;
class A<T>//注意这个类的写法,<T>代表的是一种数据类型(如int,string,byte等)
{
    
private T[] stack;//定义数据类型为T的数组
    private int count;
    
public A(int size)
    {
        stack
=new T[size];
        count
=0;
    }
    
public void input(T ip)
    {
        stack[count
++]=ip;
    }
    
public T output()
    {
        
return stack[--count];
    }
}
class B
{
    
static void Main()
    {
        A
<string> a=new A<string> (10);//实例化定义的类,这里T指代的是string类型的。
        System.Console .WriteLine ("请输进栈成员:");
        
string line=Console.ReadLine ();
        
string trimLine=line.Trim();
        
string[] strList=trimLine.Split (' ');
        
int emptyCount=0;//记录空白记录的个数
        foreach(string s in strList)
        {
            
if (s.Trim ()!="")
            {
                a.input(s);
//如果上面用定义的数组用object类型,则这里是一次装箱操作
            }
            
else
            {
                emptyCount
+=1;
            }
        }
        Console.WriteLine (
"出栈顺序为:");
        
for(int i=0;i<strList.Length-emptyCount ;i++)
        {
            Console.WriteLine (a.output());
//如果上面用定义的数组用object类型,则这里是一次拆箱操作
        }
    }
}
输出结果:

抱歉!评论已关闭.