泛型

泛型就是"占位符",写代码时先用T代表类型,使用时再指定具体类型(int、string、自定义类等)。

————————————————————————————————————————————————————————————————————————————————

案例1:打印任意类型的数据
csharp
class Printer // T是占位符
{
public void Print(T data)
{
Console.WriteLine($"打印:{data}");
}
}

class Program
{
static void Main()
{
Printer p1 = new Printer();
p1.Print(100); // 打印:100

Printer p2 = new Printer();
p2.Print("你好"); // 打印:你好

Printer p3 = new Printer();
p3.Print(3.14); // 打印:3.14
}
}
一个Printer类,能打印int、string、double...什么类型都能打。

————————————————————————————————————————————————————————————————————————————————

案例2:储物箱(存和取)
csharp
class Box
{
private T item;

public void Put(T thing) { item = thing; }
public T Get() { return item; }
}

class Program
{
static void Main()
{
Box box1 = new Box();
box1.Put("手机");
Console.WriteLine(box1.Get()); // 手机

Box box2 = new Box();
box2.Put(123);
Console.WriteLine(box2.Get()); // 123
}
}
同样的存/取逻辑,可以放字符串,也可以放数字,类型安全(box1不能放数字)。

————————————————————————————————————————————————————————————————————————————————

案例3:泛型方法(比较两个数是否相等)
csharp
class Program
{
static bool IsEqual(T a, T b)
{
return a.Equals(b);
}

static void Main()
{
Console.WriteLine(IsEqual(10, 10)); // True
Console.WriteLine(IsEqual("abc", "ABC")); // False
Console.WriteLine(IsEqual(3.14, 3.14)); // True
}
}
泛型方法不用定义泛型类,直接在方法上用,比较任意类型。

posted @ 2026-08-07 16:44  菜鸟的奋斗军  阅读(3)  评论(0)    收藏  举报