泛型

泛型
(简单的说说泛型)
泛型是.NET 2.0 新引入的一个功能,在处理很多问题时为我们提供了方便
比如以前我们象动态数组中插入元素,然后把插入的元素打印出来。
public static void Main(string[] args)
{
   //Value types are automatically boxed when
   //passed to a member requesting an object
   ArrayList myInts = new ArrayList();
   myInts.Add(10);
   Console.WriteLine("Value of your int:{0}",
                     (int)myInts[0]);//unboxed
   Console.ReadLine();
}

如果我们用了泛型
static void Main(string[] args)
{
   // No boxing!
   List<int> myInts = new List<int>();
   myInts.Add(5);
   // No unboxing!
   int i = myInts[0];
}
没有用到开箱和装箱操作


在看看一个泛型函数
static void Swap<T>(ref T a, ref T b)
{
    Console.WriteLine("You sent the Swap() method a {0}",
    typeof(T));
    T temp;
    temp = a;
    a = b;
    b = temp;
}
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Generics *****/n");
// Swap 2 ints.
int a = 10, b = 90;
Console.WriteLine("Before swap: {0}, {1}", a, b);
Swap<int>(ref a, ref b);
Console.WriteLine("After swap: {0}, {1}", a, b);
Console.WriteLine();

// Swap 2 strings.
string s1 = "Hello", s2 = "There";
Console.WriteLine("Before swap: {0} {1}!", s1, s2);
Swap<string>(ref s1, ref s2);
Console.WriteLine("After swap: {0} {1}!", s1, s2);
Console.ReadLine();
}
对不同的T类型进行了不同的操作,比以前的方法简单多了。
泛型还在其他方面得到充分的运用。

详细的内容可以查阅
<<c sharp 2005 and the dot NET2.0 Platform>>

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值