分享

c#泛型是什么

 悦光阴 2021-03-27

泛型的本质是类型参数化或参数化类型,在不创建新的类型的情况下,通过泛型指定的不同类型来控制形参具体限制的类型。

泛型是 2.0 版 C# 语言和 公共语言运行库 (CLR) 中的一个新 功能。泛型将类型参数的概念引入 .NET Framework,类型参数使得设计如下类和方法成为可能:这些类和方法将一个或多个类型的指定推迟到客户端代码声明并实例化该类或方法的时候。例如,通过使用泛型类型参数 T,您可以编写其他客户端代码能够使用的单个类,而不致引入运行时强制转换或装箱操作的成本或风险。

1.基础类库中的泛型

泛型类或接口

描述

对应的非泛型类型

Collection<T>

ICollection<T>

为泛型容器提供基类

CollectionBase

ICollection

Comparer<T>

IComparer<T>

IComparable<T>

比较两个相同泛型类型的对象是否相等、可排序。

Comparer

IComparer

IComparable

Dictionary<K, V>

IDictionary<K,V>

表示用键组织的键/值对集合。

Hashtable

IDictionary

Dictionary<K, V>.KeyCollection

表示Dictionary<K, V>中键的集合。

None.

Dictionary<K, V>.ValueCollection

表示Dictionary<K, V>中值的集合。

None.

IEnumerable<T>

IEnumerator<T>

表示可以使用foreach 迭代的集合。

IEnumerable

IEnumerator

KeyedCollection<T, U>

表示有键值的集合。

KeyedCollection

LinkedList<T>

表示双向链表。

None.

LinkedListNode<T>

表示LinkedList<T>中的节点。

None.

List<T>

IList<T>

使用大小可按需动态增加的数组实现 IList 接口

ArrayList

IList

Queue<T>

表示对象的先进先出集合。

Queue

ReadOnlyCollection<T>

为泛型只读容器提供基类。

ReadOnlyCollectionBase

SortedDictionary<K, V>

 表示键/值对的集合,这些键和值按键排序并可按照键访问,实现IComparer<T>接口。

SortedList

Stack<T>

表示对象的简单的后进先出集合。

Stack

2.示例

// Declare the generic class

public class GenericList<T>

{

void Add(T input) { }

}

class TestGenericList

{

private class ExampleClass { }

static void Main()

{

// Declare a list of type int

GenericList<int> list1 = new GenericList<int>();

// Declare a list of type string

GenericList<string> list2 = new GenericList<string>();

// Declare a list of type ExampleClass

GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();

}

}

3.用途

使用泛型类型可以最大限度地重用代码、保护类型的安全以及提高性能。

泛型最常见的用途是创建集合类。

.NET Framework 类库在 System.Collections.Generic 命名空间中包含几个新的泛型集合类。应尽可能地使用这些类来代替普通的类,如 System.Collections 命名空间中的 ArrayList

您可以创建自己的泛型接口、 泛型类、泛型方法、泛型事件和泛型委托。

可以对 泛型类进行约束以访问特定数据类型的方法。

关于泛型 数据类型中使用的类型的信息可在运行时通过反射获取。

4.练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
}

//泛型类
static T GetT<T>() where T:new()
{
return new T();
}

//泛型方法
static void create<K>(K stu) where K: MiddleStu
{
stu.Say();
}
}

//泛型接口
interface Stu
{
void Say();
}
//实现接口
class MiddleStu : Stu
{
public void Say()
{
throw new NotImplementedException();
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多