上一篇: C# 集合(Collection)
下一篇: C# 匿名方法
C# 泛型(Generic)
在本教程中,您将学习如何在 C# 中使用泛型。泛型允许您编写灵活且可重用的类和方法,同时保持类型安全。
基本概念
以下是与 C# 泛型相关的基本概念:
- 泛型 :一种编程特性,允许您编写适用于多种数据类型的类、结构、接口和方法,而无需为每种类型重复编写实现。
- 类型参数 :用于表示未指定类型的占位符,在定义泛型类或方法时使用。
创建泛型类
首先,创建一个简单的自定义泛型集合类 MyList
,它可以存储任意类型的元素。
public class MyList<T> { private List<T> _items = new List<T>(); public void Add(T item) { _items.Add(item); } public T GetItem(int index) { return _items[index]; } public int Count => _items.Count; }
在这个例子中,我们使用尖括号 <T>
定义了一个类型参数 T
,表示列表中的元素类型。然后,我们使用 List<T>
实现了一个泛型集合,并提供了用于添加和获取元素的方法。
使用泛型类
现在,您可以创建不同类型的 MyList
实例,同时保持类型安全。
class Program { static void Main(string[] args) { // 创建一个存储整数的 MyList 实例 MyList<int> intList = new MyList<int>(); intList.Add(1); intList.Add(2); Console.WriteLine("First integer: " + intList.GetItem(0)); // 创建一个存储字符串的 MyList 实例 MyList<string> strList = new MyList<string>(); strList.Add("Hello"); strList.Add("World"); Console.WriteLine("First string: " + strList.GetItem(0)); Console.ReadLine(); } }
输出结果:
First integer: 1 First string: Hello
创建泛型方法
您还可以为类创建泛型方法。以下是一个将两个参数互换顺序的简单实例:
public class Util { public static void Swap<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; } }
在这个例子中,我们使用类型参数 <T>
定义了一个名为 Swap
的泛型方法。通过使用泛型,这个方法可以用于交换任意类型的值。
使用泛型方法
现在,您可以使用泛型方法来交换不同类型的值,同时保持类型安全。
class Program { static void Main(string[] args) { int a = 1; int b = 2; Console.WriteLine($"Before swap: a = {a}, b = {b}"); Util.Swap(ref a, ref b); Console.WriteLine($"After swap: a = {a}, b = {b}"); string s1 = "Hello"; string s2 = "World"; Console.WriteLine($"\nBefore swap: s1 = {s1}, s2 = {s2}"); Util.Swap(ref s1, ref s2); Console.WriteLine($"After swap: s1 = {s1}, s2 = {s2}"); Console.ReadLine(); } }
输出结果:
Before swap: a = 1, b = 2 After swap: a = 2, b = 1 Before swap: s1 = Hello, s2 = World After swap: s1 = World, s2 = Hello
总结
在本教程中,您学习了如何在 C# 中创建和使用泛型类和方法。