.net中的泛型

.net中的泛型

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

泛型可以用于  类、方法、委托、事件等

下面先写一个简单的泛型

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();
        }
    }
}

泛型方法可以出现在泛型或非泛型类型上。需要注意的是,并不是只要方法属于泛型类型,或者甚至是方法的形参的类型是封闭类型的泛型参数,就可以说方法是泛型方法。只有当方法具有它自己的类型参数列表时,才能称其为泛型方法。在下面的代码中,只有方法 G 是泛型方法。
class A
{
    T G<T>(T arg) {...}
}
class Generic<T>
{
    T M(T arg) {...}
}



泛型的Where

  泛型的Where能够对类型参数作出限定。有以下几种方式。

  ·where T : struct 限制类型参数T必须继承自System.ValueType。
 
  ·where T : class 限制类型参数T必须是引用类型,也就是不能继承自System.ValueType。

  ·where T : new() 限制类型参数T必须有一个缺省的构造函数

  ·where T : NameOfClass 限制类型参数T必须继承自某个类或实现某个接口。

  以上这些限定可以组合使用,比如: public class Point where T : class, IComparable, new()

 

例如:
    class Person<T> where T:class
    {
       
    }

    class Program
    {
        static void Main(string[] args)
        {
          
            Person<int> bb = new Person<int>(); //報錯,
错误 1 类型“int”必须是引用类型才能用作泛型类型或方法“ConsoleApplication1.Person<T>”中的参数“T” 

        }

    }


原文:http://www.cnblogs.com/wang123/archive/2007/08/06/844752.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值