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

相关推荐
hez201020 小时前
Runtime Async - 步入高性能异步时代
c#·.net·.net core·clr
mudtools1 天前
.NET驾驭Word之力:玩转文本与格式
c#·.net
唐青枫2 天前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools2 天前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
大飞pkz2 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
唐青枫3 天前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
未来之窗软件服务3 天前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
1uther3 天前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
阿幸软件杂货间3 天前
Office转PDF转换器v1.0.py
开发语言·pdf·c#
sali-tec3 天前
C# 基于halcon的视觉工作流-章34-环状测量
开发语言·图像处理·算法·计算机视觉·c#