C# 中的泛型提供了一种使用占位符类型定义类、接口、方法和委托的方法。然后,在创建泛型类型的实例或调用泛型方法时,可以将这些占位符类型(称为类型参数)替换为实际类型。泛型允许您创建可以处理任何数据类型的组件,从而使您能够编写更灵活和可重用的代码。
C# 中的泛型和示例
2.它有一个私有整数**_count**,用于跟踪列表中的元素数量。
3. 它有一个构造函数,该构造函数以指定的容量初始化 _fruitItems 数组并将 _count 设置为 0。
4.它有一个Add方法,可以将元素添加到列表中。该方法将 T 类型的项作为参数,将其分配给 _fruitItems 数组中的下一个可用索引,并递增_count。
5.它有一个Get方法,可以从指定索引处的列表中检索元素。它返回 _fruitItems 数组中指定索引处的元素。
2. 它将两个整数 10 和 20 添加到 priceList 中
3. 它打印 priceList 的第一个元素,即 10。
4. 它创建另一个名为 nameList 的 FruitList 实例,以存储容量为 3 的字符串。
5. 它向 nameList 添加了两个字符串,“Apple”和“Mango”。
6.它尝试将nameList直接添加到名为fruitNameList的FruitList的新实例中,这将不起作用,因为Add需要T类型的单个项目。
7. 它创建一个名为 pricesList 的列表,其中包含整数 12、16、8 和 22。
8.它尝试将pricesList直接添加到名为fruitPriceList的FruitList的新实例中,由于与上述相同的原因,该实例将无法工作。
9. 它打印 fruitPriceList 的第四个元素,应为 8。
using System;
public class FruitList<T>
{
private T[] _fruitItems; // here we declared an array (_fruitItems) of elements of type T
private int _count; // here we declared an interger type (_count) variable
// here we create FruitList class constructor that will call when instance of FruitList class will create.
public FruitList(int capacity)
{
_fruitItems = new T[capacity];
_count = 0;
}
// here we created a (Add) method that will receive any type of T item these items can be integer or string or any other data type.
public void Add(T item)
{
_fruitItems[_count] = item;
_count++;
}
// here we created (Get) method that will receive integer value and will return Type T item of the array Type T.
public T Get(int index)
{
return _fruitItems[index];
}
}
class CSharpProgram
{
public static void Main(string[] args)
{
// here we are creating an instance of FruitList with integer data type with size length 5.
// this mean a priceList array of FruitList integer data type can store 5 integer items.
FruitList<int> priceList = new FruitList<int>(5);
priceList.Add(10); // here we are calling Add method of Type T
priceList.Add(20); // here we are calling Add method of Type T
Console.WriteLine(priceList.Get(0)); // Output: 10
// here we are creating an instance of FruitList with string data type with size length 3.
// this mean a nameList array of FruitList string data type can store 3 string items.
FruitList<string> nameList = new FruitList<string>(3);
nameList.Add("Apple");
nameList.Add("Mango");
Console.WriteLine(nameList.Get(1)); // Output: Mango
}
}
10
Mango
2. 它有一个 T[] 类型的私有数组**_fruitItems**来存储元素。
3.它有一个私有整数**_count**,用于跟踪列表中的元素数量。
4. 它有一个构造函数,该构造函数以指定容量初始化 _fruitItems 数组并将 _count设置为 0。
5.它有一个Add方法,可以将元素添加到列表中。该方法将 List 作为参数,并循环访问其项,将每个项添加到**_fruitItems数组中并递增_count**。
6.它有一个Get方法,用于从指定索引处的列表中检索元素。它返回 _fruitItems 数组中指定索引处的元素。
2. 它创建一个名为 fruitNameList 的 FruitList 实例,容量为 3。
3.它尝试将namesList直接添加到fruitNameList中,这现在是可能的,因为Add方法现在接受List。
4. 它打印 fruitNameList 的第二个元素,预计为 “Orange”。
5. 它创建一个名为 pricesList 的列表,其中包含整数 12、16、8 和 22。
6. 它创建一个名为 fruitPriceList 的 FruitList 实例,容量为 4。
7. 它尝试将 pricesList 直接添加到 fruitPriceList 中,类似于上述。
8. 它打印 fruitPriceList 的第四个元素,预计为 8。
using System;
public class FruitList<T>
{
private T[] _fruitItems; // here we declared an array (_fruitItems) of elements of type T
private int _count; // here we declared an interger type (_count) variable
// here we create FruitList class constructor that will call when instance of FruitList class will create.
public FruitList(int capacity)
{
_fruitItems = new T[capacity];
_count = 0;
}
// here we created a (Add) method that will receive any type of List item these items can be integer or string or any other data type.
public void Add(List<T> items)
{
foreach (T item in items)
{
_fruitItems[_count] = item;
_count++;
}
}
// here we created (Get) method that will receive integer value and will return Type T item of the array Type T.
public T Get(int index)
{
return _fruitItems[index];
}
}
class CSharpProgram
{
public static void Main(string[] args)
{
List<string> namesList = new List<string>() {"Cherry", "Orange", "Banana" };
FruitList<string> fruitNameList = new FruitList<string>(3);
fruitNameList.Add(namesList);
Console.WriteLine(fruitNameList.Get(1)); // Output: Orange
List<int> pricesList = new List<int>() {12, 16, 8, 22};
FruitList<int> fruitPriceList = new FruitList<int>(4);
fruitPriceList.Add(pricesList);
Console.WriteLine(fruitPriceList.Get(3)); // Output: 8
}
}
Orange
22
2. 它在交换之前打印 x 和 y 的值。
3. 它调用 Swap 方法,将 x 和 y 作为参数传递。由于 Swap 是一种通用方法,因此它从传递给它的参数中推断出类型 int。
4. 交换后打印 x 和 y 的值,表明它们已被成功交换。
5. 然后,它声明并初始化两个字符串变量 str1 和 str2。
6. 它在交换之前打印 str1 和 str2 的值。
7. 它再次调用 Swap 方法,将 str1 和 str2 作为参数传递。同样,为泛型方法推断类型字符串。
8. 最后,它打印了交换后的 str1 和 str2 的值,表明字符串也已成功交换。
using System;
public class GenericMethodClass<T>
{
// Generic method to swap two values of any data type
public void Swap(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
}
class CSharpProgram
{
public static void Main(string[] args)
{
int x = 5;
int y = 10;
Console.WriteLine($"Before swapping: x = {x}, y = {y}");
// Calling generic method to swap integers
GenericMethodClass<int> genericNumList = new GenericMethodClass<int>();
genericNumList.Swap(ref x, ref y);
Console.WriteLine($"After swapping: x = {x}, y = {y}");
string str1 = "Hello";
string str2 = "World";
Console.WriteLine($"Before swapping: str1 = {str1}, str2 = {str2}");
// Calling generic method to swap strings
GenericMethodClass<string> genericStringList = new GenericMethodClass<string>();
genericStringList.Swap(ref str1, ref str2);
Console.WriteLine($"After swapping: str1 = {str1}, str2 = {str2}");
}
}
Before swapping: x = 5, y = 10
After swapping: x = 10, y = 5
Before swapping: str1 = Hello, str2 = World
After swapping: str1 = World, str2 = Hello
在此示例中,Swap 方法使用类型参数 T 进行定义。此 T 可以表示任何数据类型。在该方法内部,我们声明了 T (temp) 类型的变量来执行交换操作。然后,在 Main 方法中,我们使用不同的数据类型**(int 和 string)**调用 Swap 方法。编译器会根据传递的参数自动确定适当的类型。
using System;
using System.Collections;
// Define a generic class with a constraint
public class SimpleClass<T> where T : IComparable
{
private T[] arrayFruit;
public SimpleClass(int size)
{
arrayFruit = new T[size];
}
// Method to find the maximum value in the array
public T FindMax()
{
T max = arrayFruit[0];
foreach (T item in arrayFruit)
{
if (item.CompareTo(max) > 0)
{
max = item;
}
}
return max;
}
// Method to add an item to the array
public void AddItem(int index, T item)
{
arrayFruit[index] = item;
}
}
class CSharpProgram
{
public static void Main(string[] args)
{
// Create an instance of SimpleClass with int as the type argument
SimpleClass<int> numArray = new SimpleClass<int>(3);
numArray.AddItem(0, 5);
numArray.AddItem(1, 10);
numArray.AddItem(2, 3);
// Find the maximum value in the int array
int maxNum = numArray.FindMax();
Console.WriteLine("Maximum value in int array: " + maxNum);
// Create an instance of MyClass with string as the type argument
SimpleClass<string> stringArray = new SimpleClass<string>(3);
stringArray.AddItem(0, "apple");
stringArray.AddItem(1, "banana");
stringArray.AddItem(2, "orange");
// Find the maximum value in the string array
string maxString = stringArray.FindMax();
Console.WriteLine("Maximum value in string array: " + maxString);
}
}
Maximum value in int array: 10
Maximum value in string array: orange
在此示例中,泛型类 SimpleClass 使用 where T : IComparable 进行约束。这意味着类型参数 T 必须实现 IComparable 接口,从而允许我们在 FindMax 方法中使用 CompareTo 方法来比较 T 类型的对象。此约束可确保 FindMax 方法只能使用支持比较操作的类型进行调用。