当前位置:首页 > 网络编程 > 软件语言 > .NET > .net中的泛型

.net中的泛型

点击次数:57 次 发布日期:2008-11-06 07:53:09 作者:源代码网
源代码网推荐
广告载入中

源代码网整理以下泛型把类或方法的类型的确定推迟到实例化该类或方法的时候 ,也就是说刚开始声明是不指定类型,等到要使用(实例化)时再指定类型

源代码网整理以下泛型可以用于  类、方法、委托、事件等

源代码网整理以下下面先写一个简单的泛型

源代码网整理以下public class GenericClass<T>

源代码网整理以下{

源代码网整理以下          void SomeMethod(  T   t  )

源代码网整理以下          {

源代码网整理以下                   //do something

源代码网整理以下          }

源代码网整理以下}

源代码网整理以下其使用方法如下:

源代码网整理以下实例化一个类

源代码网整理以下GenericClass<int> gci=new GenericClass<int>();方法SomeMethod就具有整数类型的参数了

源代码网整理以下下面写一个例子

源代码网整理以下using System;
using System.Collections.Generic;
using System.Text;

源代码网整理以下namespace example
{
    class GenericClass<T>
    {
        public void PrintType(T t)
        {
            Console.WriteLine("Value:{0}    Type:{1}",t,t.GetType());
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            GenericClass<int> gci = new GenericClass<int>();
            gci.PrintType(i);

源代码网整理以下            string s = "hello";
            GenericClass<string> gcs = new GenericClass<string>();
            gcs.PrintType(s);
            Console.ReadLine();
        }
    }
}


源代码网推荐

源代码网供稿.
网友评论 (0)
会员中心
网络编程
本站推荐
网络编程之精华