public class MyGenericClass where T : cl">

c#泛型怎么使用

来源:这里教程网 时间:2026-02-21 16:48:59 作者:

C# 中泛型的使用

泛型是 C# 中强大的功能,它允许创建可用于各种数据类型的类、方法和接口。

什么是泛型?

泛型是使用类型参数的类、方法或接口。类型参数充当占位符,允许泛型代码与任何类型一起使用。

如何使用泛型?

1. 声明泛型类型

用关键字

where
声明类型参数和约束。例如:

<code class="csharp">public class MyGenericClass<T> where T : class
{
    public T Value { get; set; }
}</code>

2. 使用泛型类型

像使用普通类型一样使用泛型类型。例如:

<code class="csharp">MyGenericClass<string> myStringClass = new MyGenericClass<string>();
myStringClass.Value = "Hello World!";</code>

3. 声明泛型方法

用关键字

where
声明类型参数和约束。例如:

<code class="csharp">public static void Swap<T>(ref T a, ref T b) where T : struct
{
    T temp = a;
    a = b;
    b = temp;
}</code>

4. 使用泛型方法

像使用普通方法一样使用泛型方法。例如:

<code class="csharp">int a = 10, b = 20;
Swap(ref a, ref b);
Console.WriteLine($"a: {a}, b: {b}");</code>

优势

泛型使用以下优势:

重用性:泛型代码可以与任何类型一起使用,从而提高重用性。 类型安全性:泛型确保只使用与类型参数兼容的类型,从而提高类型安全性。 简化代码:泛型消除对反射或装箱/拆箱操作的需要,从而简化代码。 性能:对于值类型,泛型代码可以比非泛型代码更快。

相关推荐