
泛型是在 C# 2.0 版本中添加的,是该语言中最重要的概念之一。它们使您能够编写在编译时类型安全的可重用、高性能代码。使用泛型,您可以在代码中使用某种类型,而无需事先了解该类型。
泛型在 .NET 中的许多地方使用,包括集合、委托和异步代码。使用泛型,您不需要事先知道集合的大小,并且可以将泛型与任何元素类型一起使用,甚至是特定于您的代码的自定义数据类型。 C# 提供对泛型类型(类、接口等)和泛型方法的支持。
在泛型中,您有类型参数和类型参数。这类似于具有参数的方法,您可以将参数传递给该方法。
声明泛型类型的语法由位于尖括号中的类型参数组成。类型的名称。例如,Locator
public class Locator<T>
{
}要创建 Locator
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
public class LinkedList<T> : IEnumerable<T>
泛型方法只是声明类型参数的方法,您可以在方法内部使用该类型参数并将其用作参数和返回类型。在下面的示例中,Swap
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;
}
}CSharp a = 3, b = 5
以上就是解释泛型在 C# 中的工作原理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号