C#语言基础-泛型
1、泛型允许类、接口、结构、委托和方法通过它们所存储和操作的数据的类型来指定类型。
2、这些类和方法将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。
3、和使用Object类相比,泛型降低了装箱和拆箱的负担,减少了类型转换所带来的错误。
4、使用泛型类型可以最大限度地重用代码,保护类型的安全以及提高性能。
5、泛型最常见的用途是创建集合类。
public class StackObj
{
object[] items = new object[100];
int count=0;
public void Push(object item)
{
items[count] = item;
count++;
}
public object Pop()
{
return items[count - 1];
}
}
/// <summary>
/// 泛型
/// </summary>
/// <typeparam name="T"></typeparam>
public class Stack<T>
{
T[] items = new T[100];
int count;
public void Push(T item)
{
items[count] = item;
count++;
}
public T Pop() { return items[count - 1]; }
}
class Program
{
static void Main(string[] args)
{
StackObj stack = new StackObj();
stack.Push(3);
int i = (int)stack.Pop();
//string s = (string)stack.Pop();//编译通过,但运行会报错
Stack<int> stackInt = new Stack<int>();
stackInt.Push(3);
int i = (int)stackInt.Pop();
//string s = (string)stackInt.Pop();//编译 不通过,
Stack<string> stackString = new Stack<string>();
stackString.Push("This i a demo about the <T>");
string demoStr = (string)stackString.Pop();
Stack<double> stackdouble = new Stack<double>();
}
}
{
object[] items = new object[100];
int count=0;
public void Push(object item)
{
items[count] = item;
count++;
}
public object Pop()
{
return items[count - 1];
}
}
/// <summary>
/// 泛型
/// </summary>
/// <typeparam name="T"></typeparam>
public class Stack<T>
{
T[] items = new T[100];
int count;
public void Push(T item)
{
items[count] = item;
count++;
}
public T Pop() { return items[count - 1]; }
}
class Program
{
static void Main(string[] args)
{
StackObj stack = new StackObj();
stack.Push(3);
int i = (int)stack.Pop();
//string s = (string)stack.Pop();//编译通过,但运行会报错
Stack<int> stackInt = new Stack<int>();
stackInt.Push(3);
int i = (int)stackInt.Pop();
//string s = (string)stackInt.Pop();//编译 不通过,
Stack<string> stackString = new Stack<string>();
stackString.Push("This i a demo about the <T>");
string demoStr = (string)stackString.Pop();
Stack<double> stackdouble = new Stack<double>();
}
}

浙公网安备 33010602011771号