泛型 的存在是为了避免类型膨胀 和 成员膨胀
先是类膨胀
创建 苹果类 和 书类
苹果类包含属性为 颜色
书类包含属性为 书名
class Apple
{
public string Color { get; set; }
}
class Book
{
public string Name { get; set; }
}
货物 都要用 盒子进行包装 若不同的盒子都装载不同的货物
那么 若有 苹果 书 南瓜 可乐 等货物 就需要有 这么多 类的盒子
太夸张了 肯定不行
这就要一个 泛型
泛型创建后 在使用时 只需要在类后添加类型 系统便会自动推断出来 格式
创建 box类
//使用<T>使类 Box泛型化
class Box<TCargo>
{
public TCargo cargo { get; set; }
}
//调用泛型类
//初始化一个Apple类 命名为 redapple
Apple redapple = new Apple() {Color = "red" };
//调用泛型类
Box<Apple> applebox = new Box<Apple>() { cargo = redapple };
Console.WriteLine(applebox.cargo.Color);
这就是 泛型类解决类膨胀的例子
成员膨胀
使用一个拉链 算法作为示范
拉链算法就是将两个数组 以互相插入的方式(如同拉链)生成一个新数组并且输出
可以发现 T[] 用于取代原本的int[] 或者double[]
static T[] Zip<T>(T[] a, T[]b)
{
T[] zipped = new T[a.Length+b.Length];
int ai = 0; int bi = 0;int zi = 0;
do
{
if (ai < a.Length)
{
zipped[zi++] = a[ai++];
}
if (bi < b.Length)
{
zipped[zi++] = b[bi++];
}
}
while (ai<a.Length || bi<b.Length);
return zipped;
}
输出到static void Main(string[] args)
int[] a1 = {1,2,3,4,5};
int[] a2 = { 1, 2, 3, 4, 5,6};
string[] a3 = {"s","b","s", };
string[] a4 = { "s", "b", "s", };
var result = Suanfa( a3, a4);
// Console.WriteLine(string.Join(",",result));
Console.WriteLine(string.Join(":",result));
static int Suanfa(int x, int y)
{
return x + y;
}
static double Add(double x, double y)
{
double x + y;
}
委托的泛型使用
Action用于 无返回值 方法
Func用于 有返回值
static void Say(string str)
{
Console.WriteLine($"Hello,{str}");
}
//Action<>
Action<string> b1 = Say;
Action<int> a1 = Mul;
//action调用格式 只有一个参数 所以 <>中只包含一个
--------------func分割线--------
public static int Mult(int a, int b)
{
return a * b;
}
Func<int, int, int> d1 = Mult;
Console.WriteLine(d1(3, 8));
第三个int指代输出 的 return a * b 参数 第一个第二个是 a,b