c# 定义泛型

本文详细介绍了如何在C#中使用泛型编写通用代码,通过MyGenericClass<T>类和其成员变量与泛型方法,展示了如何在不同数据类型间操作,以及在Main方法中实例化和调用这些泛型类的例子。
摘要由CSDN通过智能技术生成

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

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

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值