Files
Csharp/C#进阶/Lesson5_泛型/Program.cs
T
2025-10-13 09:28:20 +08:00

137 lines
3.1 KiB
C#

using System.Runtime.InteropServices;
using static System.Net.Mime.MediaTypeNames;
namespace Lesson5_泛型
{
#region 知识点一 泛型是什么
//泛型实现了类型参数化,达到了代码重用的目的
//通过类型参数化来实现同一份代码上操作多种类型
//泛型相当于类型占位符
//定义类或方法时使用替代符代表变量类型
//当真正使用类或方法时再具体指定类型
#endregion
#region 知识点二 泛型分类
//泛型类和泛型接口
//基本语法:
//class 类名<泛型占位符>
//interface 接口名<泛型占位符>
//泛型占位语法
//基本语法:函数名<泛型占位符>(参数列表)
//注意:泛型占位符可以有多个,用逗号分开
#endregion
#region 知识点三 泛型类和接口
class Test<T>
{
public T value;
}
class Test2<T1, T2, K, M, L>
{
public T1 value1;
public T2 value2;
public K value3;
public M value4;
public L value5;
}
interface TestInterface<T>
{
T value
{
get
{
return value;
}
set
{
this.value = value;
}
}
}
class Test4 : TestInterface<int>
{
//接口实现
}
#endregion
#region 知识点四 泛型方法
class Test5
{
public void TestFun<T>(T value)
{
Console.WriteLine(value);
}
public void TestFun<T>()
{
//用泛型类型做逻辑处理
T t = default(T);//
}
public T TestFun<T>(string v)
{
return default(T);
}
public void TestFun<T, K, M>(T t,K k,M m)
{
}
}
class Test5<T>//泛型类和普通类即使只是多加一个泛型也是两个类
{
public T value;
//下面这个不是泛型方法,因为T是泛型类声明时指定的
//我们就不能再手动指定类型了
public void TestFun(T t)
{
}
public void TestFun<K>(K k)
{
}
}
#endregion
#region 知识点五 泛型的作用
//1.不同类型的对象的相同逻辑处理可以用泛型
//2.使用泛型可以一定程度上避免装箱拆箱
//举例:优化ArrayList
class ArrayList<T>
{
private T[] array;//实现它的增删查改
}
#endregion
internal class Program
{
static void Main(string[] args)
{
Test<int> t1 = new Test<int>();
t1.value = 10;
Console.WriteLine(t1.value);
Test<string> t2 = new Test<string>();
t2.value = "test";
Console.WriteLine(t2.value);
Test5 t3 = new Test5();
t3.TestFun<string>("123");
Test5<int> t4 = new Test5<int>();
//t4.TestFun<("123");//不能是string了因为声明时是int
t4.TestFun<string>("123");
t4.TestFun<float>(1.23f);
}
}
}