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

相关推荐
MyBFuture2 小时前
C#接口与抽象类:关键区别详解
开发语言·c#·visual studio
曹牧3 小时前
C#:记录日志
服务器·前端·c#
心疼你的一切6 小时前
三菱FX5U PLC与C#通信开发指南
开发语言·单片机·c#
czhc11400756636 小时前
C# 1221
java·servlet·c#
yong99908 小时前
C#实现OPC客户端与S7-1200 PLC的通信
开发语言·网络·算法·c#
先生沉默先9 小时前
c#Socket学习,使用Socket创建一个在线聊天,服务端功能实现,(3)
服务器·学习·c#
superman超哥9 小时前
仓颉热点代码识别深度解析
开发语言·后端·python·c#·仓颉
Lv11770089 小时前
Visual Studio中的接口
ide·笔记·c#·visual studio
阿蒙Amon10 小时前
C#每日面试题-类和结构的区别
开发语言·c#
MyBFuture12 小时前
索引器实战:对象数组访问技巧及命名空间以及项目文件规范
开发语言·前端·c#·visual studio