泛型
(简单的说说泛型)
泛型是.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>>