C#泛型是一种编写可重用代码的机制,它允许我们创建不特定于具体类型的类、接口和方法。泛型的优点是可以提高代码的可读性和安全性,同时也可以减少代码的重复性。
- 泛型类
泛型类是一种可以在类中使用类型参数的类。类中可以使用类型参数来定义字段、属性、方法等成员。下面是一个简单的泛型类的例子:
public class MyGenericClass<T>
{
private T _value;
public MyGenericClass(T value)
{
_value = value;
}
public T GetValue()
{
return _value;
}
}
在上面的例子中,我们定义了一个泛型类 MyGenericClass<T>
,其中 T
是一个类型参数。类中有一个私有字段 _value
,类型为 T
。类中有一个构造函数,参数为类型为 T
的值,并将值赋给 _value
字段。类中还有一个公共方法 GetValue()
,返回类型为 T
的值。
使用泛型类时,需要指定类型参数的具体类型。例如:
MyGenericClass<int> intClass = new MyGenericClass<int>(10);
int intValue = intClass.GetValue(); // intValue = 10
MyGenericClass<string> stringClass = new MyGenericClass<string>("Hello, world!");
string stringValue = stringClass.GetValue(); // stringValue = "Hello, world!"
在上面的例子中,我们分别创建了一个 MyGenericClass<int>
和一个 MyGenericClass<string>
的实例,分别传入了不同类型的值,并通过调用 GetValue()
方法获取了对应类型的值。
- 泛型接口
泛型接口是一种可以在接口中使用类型参数的接口。和泛型类类似,接口中的类型参数可以用于定义方法、属性、事件等成员。下面是一个简单的泛型接口的例子:
public interface IMyGenericInterface<T>
{
T GetValue();
}
在上面的例子中,我们定义了一个泛型接口 IMyGenericInterface<T>
,其中 T
是一个类型参数。接口中有一个方法 GetValue()
,返回类型为 T
的值。
使用泛型接口时,需要指定类型参数的具体类型。例如:
public class MyGenericClass<T> : IMyGenericInterface<T>
{
private T _value;
public MyGenericClass(T value)
{
_value = value;
}
public T GetValue()
{
return _value;
}
}
MyGenericClass<int> intClass = new MyGenericClass<int>(10);
int intValue = intClass.GetValue(); // intValue = 10
MyGenericClass<string> stringClass = new MyGenericClass<string>("Hello, world!");
string stringValue = stringClass.GetValue(); // stringValue = "Hello, world!"
在上面的例子中,我们创建了一个实现了泛型接口 IMyGenericInterface<T>
的泛型类 MyGenericClass<T>
,并分别使用了不同类型的值进行了实例化和调用。
- 泛型方法
泛型方法是一种可以在方法中使用类型参数的方法。和泛型类、泛型接口类似,方法中的类型参数可以用于定义参数、返回值、局部变量等。下面是一个简单的泛型方法的例子:
public class MyGenericClass<T> : IMyGenericInterface<T>
{
private T _value;
public MyGenericClass(T value)
{
_value = value;
}
public T GetValue()
{
return _value;
}
}
MyGenericClass<int> intClass = new MyGenericClass<int>(10);
int intValue = intClass.GetValue(); // intValue = 10
MyGenericClass<string> stringClass = new MyGenericClass<string>("Hello, world!");
string stringValue = stringClass.GetValue(); // stringValue = "Hello, world!"
在上面的例子中,我们定义了一个泛型方法 GetMax<T>
,其中 T
是一个类型参数。方法中有两个参数 a
和 b
,类型都为 T
。方法中使用了 where
关键字来限制 T
必须实现 IComparable<T>
接口,以便进行比较操作。方法中通过调用 CompareTo()
方法来比较 a
和 b
的大小,并返回较大的值。
使用泛型方法时,需要指定类型参数的具体类型。例如:
int intMax = GetMax<int>(10, 20); // intMax = 20
double doubleMax = GetMax<double>(10.5, 20.5); // doubleMax = 20.5
在上面的例子中,我们分别调用了 GetMax<int>
和 GetMax<double>
方法,分别传入了不同类型的参数,并获取了对应类型的返回值。
总之,C#泛型是一种非常强大的编程机制,可以帮助我们编写更加灵活和可重用的代码。通过泛型类、泛型接口和泛型方法,我们可以在不知道具体类型的情况下,编写出支持多种类型的代码。