How to define and use generic classes and methods in C#?
In C#, generic classes and methods allow you to write more flexible and reusable code. Here is an example of how to define and use generic classes and methods.
Define a generic class.
public class GenericClass<T>
{
private T _value;
public GenericClass(T value)
{
_value = value;
}
public T GetValue()
{
return _value;
}
}
Utilizing generic classes:
GenericClass<int> intGenericClass = new GenericClass<int>(10);
Console.WriteLine(intGenericClass.GetValue()); // 输出:10
GenericClass<string> stringGenericClass = new GenericClass<string>("Hello");
Console.WriteLine(stringGenericClass.GetValue()); // 输出:Hello
Define generic method:
public class GenericMethod
{
public T FindMax<T>(T[] array) where T : IComparable
{
T max = array[0];
foreach (T item in array)
{
if (item.CompareTo(max) > 0)
{
max = item;
}
}
return max;
}
}
Utilizing generic methods:
GenericMethod genericMethod = new GenericMethod();
int[] intArray = { 1, 2, 3, 4, 5 };
Console.WriteLine(genericMethod.FindMax(intArray)); // 输出:5
string[] stringArray = { "apple", "orange", "banana" };
Console.WriteLine(genericMethod.FindMax(stringArray)); // 输出:orange