泛型是在 c# 2.0 版本中添加的,是该语言中最重要的概念之一。它们使您能够编写在编译时类型安全的可重用、高性能代码。使用泛型,您可以在代码中使用某种类型,而无需事先了解该类型。
泛型在 .net 中的许多地方使用,包括集合、委托和异步代码。使用泛型,您不需要事先知道集合的大小,并且可以将泛型与任何元素类型一起使用,甚至是特定于您的代码的自定义数据类型。 c# 提供对泛型类型(类、接口等)和泛型方法的支持。
在泛型中,您有类型参数和类型参数。这类似于具有参数的方法,您可以将参数传递给该方法。
泛型类型声明泛型类型的语法由位于尖括号中的类型参数组成。类型的名称。例如,locator 是下面示例中的泛型类。
public class locator<t>{}
要创建 locator 的实例,请使用 new 关键字,后跟类的名称。但是,您可以指定要作为参数传递的实际类型,而不是 t。以下示例将字符串类型作为参数传递。
var stringlocator = new locator<string>();
您可以在类方法上使用类型参数 (t),如下例所示。
public class locator<t>{ public ilist<t> items { get; set; } public t locate(int index){ return items[index]; }}var stringlocator = new locator<string>();string item = stringlocator.locate(2);
泛型的另一个好处是编辑器提供的 intellisense。当您在 visual studio 或 vs code 中键入 stringlocator.locate(4) 并将鼠标悬停在方法名称上时;它会显示它返回一个字符串而不是 t。如果您尝试将结果分配给字符串以外的任何类型,编译器将引发错误。例如,
// error: cannot implicitly convert type 'string' to 'int' [c-sharp]csharp(cs0029)int item = stringlocator.locate(2);
从泛型基类型或泛型接口继承时,泛型类型可以使用类型形参作为类型实参。通用 linkedlist 类型实现通用 ienumerable 接口以及其他接口。
public class linkedlist<t> : ienumerable<t>
泛型方法泛型方法只是声明类型参数的方法,您可以在方法内部使用该类型参数并将其用作参数和返回类型。在下面的示例中,swap 是一个泛型方法,它采用两个 t 类型的参数并返回 t 的实例。
public class swapper{ public t swap<t>(t first, t second){ t temp = first; first = second; second = temp; return temp; }}
与泛型类型一样,当您调用泛型方法时,它将返回一个强类型变量。
var swapper = new swapper();int result = swapper.swap<int>(5, 3);
可以有多个通用参数。 system.collections.generic 命名空间中的 dictionary 类有两个类型参数,即键和值。
public class dictionary<tkey, tvalue>
最后,了解什么是通用的很重要。对于类型来说,除了枚举之外,一切都可以是泛型的。其中包括 -
类结构接口委托对于类型成员,只有方法和嵌套类型可以是泛型的。以下成员不能是通用的 -
字段属性索引器构造函数事件终结器示例 现场演示
using system;using system.collections.generic;class program{ static void main(){ var stringlocator = new locator<string>(){ items = new string[] { "javascript", "csharp", "golang" } }; string item = stringlocator.locate(1); console.writeline(item); // csharp var swapper = new swapper(); int a = 5, b = 3; int result = swapper.swap<int>(ref a, ref b); console.writeline($"a = {a}, b = {b}"); }}public class locator<t>{ public ilist<t> items { get; set; } public t locate(int index){ return items[index]; }}public class swapper{ public t swap<t>(ref t first, ref t second){ t temp = first; first = second; second = temp; return temp; }}
输出csharpa = 3, b = 5
以上就是解释泛型在 c# 中的工作原理的详细内容。