c#泛型是什么

泛型的本质是类型参数化或参数化类型,在不建立新的类型的状况下,经过泛型指定的不一样类型来控制形参具体限制的类型。数组

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

 

1.基础类库中的泛型性能

泛型类或接口学习

描述spa

对应的非泛型类型设计

Collection<T>htm

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

}

 

做者还在学习中,发现错误的请在评论区留言。  若是有客友以为文章还行的话,请点波推荐哦👍。 谢谢大家!!

相关文章
相关标签/搜索