介绍
泛型类型是类型的模板
using System;
// 定义一个泛型类
public class MyGenericClass<T>
{
public T Value { get; set; }
public MyGenericClass(T value)
{
Value = value;
}
}
// 定义一个泛型接口
public interface IMyGenericInterface<T>
{
T GetValue();
}
// 实现泛型接口
public class MyImplementation : IMyGenericInterface<int>
{
private int data;
public MyImplementation(int value)
{
data = value;
}
public int GetValue()
{
return data;
}
}
class Program
{
static void Main()
{
// 使用泛型类
MyGenericClass<int> intInstance = new MyGenericClass<int>(42);
MyGenericClass<string> stringInstance = new MyGenericClass<string>("Hello, World!");
Console.WriteLine($"Integer Value: {intInstance.Value}");
Console.WriteLine($"String Value: {stringInstance.Value}");
// 使用泛型接口
MyImplementation impl = new MyImplementation(100);
int valueFromInterface = impl.GetValue();
Console.WriteLine($"Value from interface: {valueFromInterface}");
}
}