当前位置: 移动技术网 > IT编程>开发语言>c# > C#泛型类型知识讲解

C#泛型类型知识讲解

2020年06月23日  | 移动技术网IT编程  | 我要评论
概述  泛型类和泛型方法兼具可重用性、类型安全性和效率,这是非泛型类和非泛型方法无法实现的  泛型通常与集合以及作用于集合的方法一起使用  泛型所属命名空间:system.collections.ge

概述

  泛型类和泛型方法兼具可重用性、类型安全性和效率,这是非泛型类和非泛型方法无法实现的

  泛型通常与集合以及作用于集合的方法一起使用

  泛型所属命名空间:system.collections.generic

  可以创建自定义泛型接口、泛型类、泛型方法、泛型事件和泛型委托,以提供自己的通用解决方案,设计类型安全的高效模式

  泛型允许编写一个可以与任何数据类型一起工作的类或方法

示例

using system;
using system.collections.generic;

namespace generictest
{
  public class testgeneric<t>
  {

    private t[] array;
    public testgeneric(int i)
    {
      array = new t[i + 1];
    }
    public t getitem(int index)
    {
      return array[index];
    }
    public void setitem(int index, t value)
    {
      array[index] = value;
    }
  }

  class tester
  {
    static void main(string[] args)
    {
      testgeneric<char> myarray = new testgeneric<char>(5);
      for (int i = 0; i < 5; i++)
      {
        myarray.setitem(i, (char)(i + 97));
      }

      for (int i=0; i<5; i++)
      {
        console.writeline(myarray.getitem(i));
      }
      console.writeline();
      console.readkey();
    }

  }
}

结果

约束

  对代码能够在实例化类时用于类型参数的类型种类施加限制

  约束的方式是指定t的祖先,即继承的接口或类

  代码尝试使用某个约束所不允许的类型来实例化类,则会产生编译时错误

  定义:public t getinfo<t>(string id) where t : cbaseinfo

约束限定条件

       t:struct    类型参数必须是值类型。可以指定除 nullable 以外的任何值类型

       t:class      类型参数必须是引用类型,包括任何类、接口、委托或数组类型

       t:new()      类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时new() 约束必须最后指定

       t:<基类名> 类型参数必须是指定的基类或派生自指定的基类

       t:<接口名称> 类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。

       t:u    为 t 提供的类型参数必须是为 u 提供的参数或派生自为 u 提供的参数,称为裸类型约束

例:

public class myarray<t> : b<t> where t : new() { }

定义多个类型参数和约束:

public class base<a,b,c> where a: struct
where b: new()
where c: class
{ }

泛型也可以继承泛型:

class d:c<string,int>

class e<u,v>:c<u,v>

class f<u,v>:c<string,int>

以上就是c#泛型类型知识讲解的详细内容,更多关于c#泛型类型的资料请关注移动技术网其它相关文章!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网