小编这次要给大家分享的是详解C#泛型类型,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

概述

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

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

  泛型所属命名空间: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: structwhere 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#泛型类型的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。