溫馨提示×

C#中如何創建和使用泛型

c#
小億
141
2024-04-03 15:55:59
欄目: 編程語言

在C#中,可以使用泛型來創建可以在不同數據類型下重復使用的代碼。以下是在C#中創建和使用泛型的方法:

  1. 創建泛型類:
public class GenericClass<T>
{
    public T Value { get; set; }

    public GenericClass(T value)
    {
        Value = value;
    }

    public void PrintValue()
    {
        Console.WriteLine(Value);
    }
}
  1. 使用泛型類:
GenericClass<int> intGenericClass = new GenericClass<int>(10);
intGenericClass.PrintValue();

GenericClass<string> stringGenericClass = new GenericClass<string>("Hello");
stringGenericClass.PrintValue();
  1. 創建泛型方法:
public T FindMax<T>(T[] array)
{
    if (array == null || array.Length == 0)
    {
        throw new ArgumentException("Array cannot be null or empty");
    }

    T max = array[0];
    foreach (T item in array)
    {
        if (Comparer<T>.Default.Compare(item, max) > 0)
        {
            max = item;
        }
    }

    return max;
}
  1. 使用泛型方法:
int[] intArray = { 3, 7, 2, 9, 5 };
int maxInt = FindMax(intArray);
Console.WriteLine($"Max integer: {maxInt}");

string[] stringArray = { "apple", "banana", "orange" };
string maxString = FindMax(stringArray);
Console.WriteLine($"Max string: {maxString}");

通過上述步驟,我們可以創建和使用泛型類和方法來實現通用的代碼,可以在不同類型的數據上進行操作。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女