C# 泛型

泛型是强类型语言下的特色,是为了方便我们动态编程。我们不去追究这个名词“泛型”,说白了,其实就是动态地指定一个变量的类型。泛型泛型,广泛的类型,不确定的类型。

比如:

Code
    public class TestArray
    {
        
public TestArray()
        {

            TestObject o 
= new TestObject();

            Console.WriteLine(GetValue
<TestObject>(o));
            Console.WriteLine(GetValue
<TestClass>(new TestClass()));

            Console.ReadLine();
        }

        
public string GetValue<T>(T t)
        {
            
return t.ToString();
        }
    }

如果我们不用泛型,那么我们得多写一个方法:

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharp
{
    
public class TestArray
    {
        
public TestArray()
        {

            TestObject o 
= new TestObject();

            Console.WriteLine(
"使用泛型:");
            Console.WriteLine(GetValue
<TestObject>(o));
            Console.WriteLine(GetValue
<TestClass>(new TestClass()));

            Console.WriteLine(
"不使用泛型:");
            Console.WriteLine(GetValue(o));
            Console.WriteLine(GetValue(
new TestClass()));

            Console.ReadLine();
        }

        
public string GetValue<T>(T t)
        {
            
return t.ToString();
        }

        
//不使用泛型,在参数里面明确指定变量t是TestObject类型
        public string GetValue(TestObject t)
        {
            
return t.ToString();
        }

        
//不使用泛型,在参数里面明确指定变量t是TestClass类型
        public string GetValue(TestClass t)
        {
            
return t.ToString();
        }
    }

    
public class TestObject
    {
        
public override string ToString()
        {
            
return " 我是TestObject";
        }
    }

    
public class TestClass
    {
        
public override string ToString()
        {
            
return " 我是 TestClass";
        }
    }
}

 

泛型官方参考:
http://msdn.microsoft.com/zh-cn/library/512aeb7t(VS.80).aspx
重点理解:泛型类,泛型接口,泛型方法(我们上面演示的就是泛型方法),泛型和数组.

posted @ 2009-01-08 10:57  无尽思绪  阅读(312)  评论(0编辑  收藏  举报