How to define and use generic classes in C#
In C#, generic classes can be defined by placing angle brackets <> after the class name to specify generic parameters. These classes can accept parameters of different types and use them within the class.
Here is an example of defining and using a generic class:
// 定义一个泛型类
public class MyGenericClass<T>
{
private T myGenericField;
// 构造函数
public MyGenericClass(T value)
{
myGenericField = value;
}
// 方法
public T GetGenericValue()
{
return myGenericField;
}
}
// 使用泛型类
public class Program
{
public static void Main(string[] args)
{
// 创建一个泛型类对象,指定泛型参数为int类型
MyGenericClass<int> intGenericClass = new MyGenericClass<int>(10);
// 调用泛型类的方法
int intValue = intGenericClass.GetGenericValue();
Console.WriteLine(intValue); // 输出:10
// 创建一个泛型类对象,指定泛型参数为string类型
MyGenericClass<string> stringGenericClass = new MyGenericClass<string>("Hello");
// 调用泛型类的方法
string stringValue = stringGenericClass.GetGenericValue();
Console.WriteLine(stringValue); // 输出:Hello
}
}
In the above example, MyGenericClass is a generic class with a generic parameter T. We store the value of the generic parameter passed in myGenericField field and return that value in the GetGenericValue method.
In the Main method, we first create an object of MyGenericClass
Next, we created an object of MyGenericClass
Running the above code will output:
10
Hello
This shows that generic classes are able to store and return values of different types based on the different type parameters passed in.