c# 定义泛型

在 C# 中,可以使用泛型来编写通用的代码,使得代码可以在不同的数据类型上进行操作,而不需要对每种数据类型都编写一套代码。下面是一个简单的示例,演示了如何在 C# 中定义和使用泛型:

cs 复制代码
csharp
using System;

// 定义一个泛型类
public class MyGenericClass<T>
{
    private T genericMemberVariable;

    // 构造函数
    public MyGenericClass(T value)
    {
        genericMemberVariable = value;
    }

    // 泛型方法
    public T GenericMethod(T genericParameter)
    {
        Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(), genericParameter);
        Console.WriteLine("Member variable type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
        return genericMemberVariable;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 使用泛型类,指定具体的类型
        MyGenericClass<int> intGenericClass = new MyGenericClass<int>(10);
        int result1 = intGenericClass.GenericMethod(5); // 传入 int 类型的参数

        MyGenericClass<string> stringGenericClass = new MyGenericClass<string>("Hello");
        string result2 = stringGenericClass.GenericMethod("World"); // 传入 string 类型的参数
    }
}

在上面的示例中,MyGenericClass<T> 是一个泛型类,T 是一个类型参数,可以在类中的任何地方使用。MyGenericClass<T> 类有一个成员变量 genericMemberVariable 和一个泛型方法 GenericMethod,可以接受任意类型的参数和返回值。在 Main 方法中,我们创建了两个 MyGenericClass 类的实例,一个是 MyGenericClass<int>,另一个是 MyGenericClass<string>,分别指定了 T 的具体类型为 int 和 string。然后我们调用了 GenericMethod 方法,并传入了不同类型的参数,可以看到方法能够正确地接受参数并返回结果。

相关推荐
海盗12343 小时前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
dalong109 小时前
WPF:3D甜甜圈
3d·c#·wpf·甜甜圈
神秘的MT14 小时前
C# WinForm Socket 类 常用方法 (C# .NET,TCP 场景)
服务器·网络·学习·tcp/ip·c#·winform
神罚天下ET1 天前
c# ACME client (补充)
开发语言·c#
噗噗夹的TA之旅1 天前
Shader 学习 21:自定义 Render Feature
学习·游戏·unity·c#·游戏引擎·图形渲染
脚踏实地皮皮晨1 天前
003006001_WrapPanel控件
开发语言·c#·.net·wpf·visual studio
脚踏实地皮皮晨1 天前
003005002_WPF StackPanel 基类官方类定义逐行深度解析
开发语言·windows·算法·c#·wpf·visual studio
用户298698530141 天前
Excel 转 PDF 免费在线工具,格式完美保留
人工智能·c#·excel
库拉库拉里1 天前
深入理解 C# 异步编程:同步、Task.Wait () 与 await 的本质区别及实践指南
开发语言·c#
神罚天下ET1 天前
.NET 新增功能系列文章——C# 中的新增功能
开发语言·c#·.net