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 方法,并传入了不同类型的参数,可以看到方法能够正确地接受参数并返回结果。

相关推荐
政沅同学6 小时前
C# 一种很好用的设计模式 不同对象之间进行解耦通信
设计模式·c#
咩图7 小时前
C#进程通讯-命名管道通讯
c#·命名管道·进程通讯
SunnyDays10117 小时前
如何使用 C# 高效实现 Excel 与 CSV 的互相转换
c#·excel·csv
Byron Loong8 小时前
【网络】C#TCP 通讯
网络·tcp/ip·c#
geovindu8 小时前
密码进行加盐哈希 using CSharp,Python,Go,Java
java·python·golang·c#·哈希算法
傻啦嘿哟8 小时前
Python 操作 Word 文档属性与字数统计方法详解
开发语言·c#
.NET修仙日记9 小时前
2026 .NET 面试八股文:高频题 + 答案 + 原理(基础核心篇)
云原生·面试·职场和发展·c#·.net·面试题·微软技术
君莫愁。9 小时前
【Unity】解决UGUI的Button无法点击/点击无反应的排查方案
unity·c#·游戏引擎·解决方案·ugui·按钮·button
石榴树下的七彩鱼19 小时前
图片修复 API 接入实战:网站如何自动去除图片水印(Python / PHP / C# 示例)
图像处理·后端·python·c#·php·api·图片去水印
忒可君20 小时前
C# winform 自制分页功能
android·开发语言·c#