C#入门级——泛型、泛型类、泛型接口、泛型方法和泛型委托

目录

一、泛型(generic)

二、为什么需要泛型类

类型膨胀

成员膨胀

使用object类

三、泛型的定义

定义泛型类

使用泛型类

泛型接口​​​​​​​

两种泛型接口的实现方法

泛型方法

成员膨胀

使用泛型

泛型委托

Action委托——只能引用没有返回值的方法

Func泛型委托——要有返回值

泛型委托和Lambda表达式的配合使用


一、泛型(generic)

泛型类是以实例化过程中提供的类型或类为基础建立的,可对对象进行强类型化

尖括号语法是把类型参数传送给泛型类型的方式

泛型并不限于类,还可以创建泛型接口、泛型方法(可以在非泛型类上定义),甚至泛型委托

泛化和特化是相对的

System.Collections.Generics名称空间的两个类型

类型:List               说明:T类型对象的集合

类型:Dictionary 说明:与K类型的键值相关的V类型的项的集合

前文已提及到:

C#集合、定义集合、索引符、List<T>、Dictionary<K,V>、键控集合(键值)和IDictionary_dlwlrma_516的博客-CSDN博客https://blog.csdn.net/dlwlrma_516/article/details/127139139?spm=1001.2014.3001.5501

二、为什么需要泛型类

场景:新百货商店开业,两个类,Chair类,Desk类

不同的货物要用不同的纸箱去装

类型膨胀

现在百货商店新开张,卖Chair和Desk,Chair需要用ChairCarton装,Desk需要用DeskCarton装;但是如果以后百货商店有1000种商品呢?要准备1000种纸箱吗?而且程序不好维护…

创建控制台项目

C#入门级——泛型、泛型类、泛型接口、泛型方法和泛型委托_第1张图片

C#入门级——泛型、泛型类、泛型接口、泛型方法和泛型委托_第2张图片

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Chair chair = new Chair() { Color = "Red" };
            ChairCarton chairCarton = new ChairCarton() { Cargo = chair };
            Console.WriteLine(chairCarton.Cargo.Color);

            Desk desk = new Desk() { Weight = "20kg" };
            DeskCarton deskCarton = new DeskCarton() { Cargo = desk };
            Console.WriteLine(deskCarton.Cargo.Weight);
            Console.ReadKey();
        }
    }

    class Chair
    {
        public string Color { get; set; }
    }

    class Desk
    {
        public string Weight { get; set; }
    }

    class ChairCarton
    {
        public Chair Cargo { get; set; }
    }
    class DeskCarton
    {
        public Desk Cargo { get; set; }
    }
}

成员膨胀

只准备一种纸箱,填写不同的属性,carton1实例只用到了Chair属性,没有用到Desk属性,而carton2属性则相反

以后1000种商品呢?Carton类1000个对应属性,只有1个属性能用,每次增加或减少商品,都要修改Carton类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Chair chair = new Chair() { Color = "Red" };
            Desk desk = new Desk() { Weight = "20kg" };
            Carton carton1 = new Carton() { ChairCargo = chair };
            Carton carton2 = new Carton() { DeskCargo = desk };
            Console.WriteLine(carton1.ChairCargo.Color);
            Console.WriteLine(carton2.DeskCargo.Weight);
            Console.ReadKey();
        }
    }

    class Chair
    {
        public string Color { get; set; }
    }

    class Desk
    {
        public string Weight { get; set; }
    }

    class Carton
    {
        public Chair ChairCargo { get; set; }
        public Desk DeskCargo { get; set; }
    }
}

使用object类

当把东西往盒子里装时是省事了,但是要把东西从盒子里拿出来时,访问盒子中装的东西就很麻烦

(chair实例赋值给Cargo属性,在Console.WriteLine(carton1.Cargo.时,系统在可选择下拉框中,就已经找不到chair实例下的有关属性Color,需要强制类型转换/as属性操作符)

使用?.的原因:若是个Chair类则打印Color属性,若是Desk类则不会打印Color属性


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Chair chair = new Chair() { Color = "Red" };
            Desk desk = new Desk() { Weight = "20kg" };
            Carton carton1 = new Carton() { Cargo = chair };
            Carton carton2 = new Carton() { Cargo = desk };
            Console.WriteLine((carton1.Cargo as Chair)?.Color);
            Console.WriteLine((carton2.Cargo as Desk)?.Weight);
            Console.ReadKey();

        }
    }

    class Chair
    {
        public string Color { get; set; }
    }

    class Desk
    {
        public string Weight { get; set; }
    }
    class Carton
    {
        public Object Cargo { get; set; }
    }
}

三、泛型的定义

泛型的定义:泛型类、泛型接口、泛型方法、泛型委托

定义泛型类

<类型参数>     类型参数:标识符,代表泛化的类型

创建泛型类——需在类定义中包含尖括号

class GenericClass
{

}

class Carton

TCargo类型是商品的类型(写的是类名!!)

声明属性——public TCargo Cargo{get;set;}

定义泛型Carton类

class Carton
{
	public TCargo Cargo{get;set;}
}

使用泛型类

使用泛型Carton类

泛型编程实体都不能拿来编程,想要使用泛型实体之前都必须要进行特化

特化

先将泛型Carton类先特化为装Chair的Carton类型:

Carton,相当于Chair类型替换了TCargo类型(TCargo-->Chair)

(属性:public TCargo-->public Chair         TCargo类型变成了Chair类型)

在main函数中进行特化:

Carton carton1= new Carton(){Cargo = Chair};

凡是使用到了类型参数的地方都是强类型的

Cargo属性强类型,属性类型是Chair类型,Chair类型的实例有Color这个属性

Cargo属性强类型,属性类型是Desk类型,Desk类型的实例有Weight这个属性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Chair chair = new Chair() { Color = "Red" };
            Desk desk = new Desk() { Weight = "20kg" };
            Carton carton1 = new Carton() { Cargo = chair };
            Carton carton2 = new Carton() { Cargo = desk };
            Console.WriteLine(carton1.Cargo.Color);
            Console.WriteLine(carton2.Cargo.Weight);
            Console.ReadKey();
        }
    }

    class Chair
    {
        public string Color { get; set; }
    }

    class Desk
    {
        public string Weight { get; set; }
    }

    class Carton
    {
        public TCargo Cargo { get; set; }
    }
}

泛型接口

声明接口,保证对象的唯一——具有ID属性,ID属性的类型不确定,接口改为泛型接口

类型参数:TId——ID属性的类型

接口中不能够加public,因为默认就是public

interface IUnique
{
    TId ID { get; set; }
}

Student类实现IUnique接口,派生自IUnique

类型参数:TId

如果一个类实现了泛型接口,那么它本身也是泛型的

实现接口,就必须把接口的全部成员都实现

泛型的Student类,TId类型参数只会影响到ID这个属性的类型

实现ID属性:

    interface IUnique
    {
        TId ID { get; set; }
    }

    class Student : IUnique
    { 
        public TId ID { get; set; }
    }

给Student类添加字符串类型的名字Name

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            
        }
    }

    interface IUnique
    {
        TId ID { get; set; }
    }

    class Student : IUnique
    { 
        public TId ID { get; set; }
        public string Name { get; set; }
    }
}

main函数中使用Student类

设置Student类的ID是整数:Student

特化Student类后,使用Student类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu.ID = 10000;
            stu.Name = "Tom";
        }
    }

    interface IUnique
    {
        TId ID { get; set; }
    }

    class Student : IUnique
    { 
        public TId ID { get; set; }
        public string Name { get; set; }
    }
}

随着学校的扩张,ID需要从int改为无符号长整型

ulong作为类型参数传给泛型student类,id的类型就是ulong型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu.ID = 10000000000000000;
            stu.Name = "Tom";
        }
    }

    interface IUnique
    {
        TId ID { get; set; }
    }

    class Student : IUnique
    { 
        public TId ID { get; set; }
        public string Name { get; set; }
    }
}

两种泛型接口的实现方法

1、声明Student类时,实现IUnique泛型接口,这时Student类成为泛型类

(前面提及到的情况)

2、实行泛型接口时,实现的是特化后的泛型接口,类不再是泛型类

(下面提及到的情况)

实现IUnique接口时,不再用TId,确定ID的类型一定就是ulong,直接特化了接口,Student类不是泛型类了

当声明一个类时,在实现接口时,就已经把接口特化了,类实现的就是特化后的泛型接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu.ID = 10000000000000000;
        }
    }

    interface IUnique
    {
        TId ID { get; set; }
    }

    class Student : IUnique
    { 
        public ulong ID { get; set; }
    }
}

添加Name属性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student();
            stu.ID = 10000000000000000;
            stu.Name = "Tom";
        }
    }

    interface IUnique
    {
        TId ID { get; set; }
    }

    class Student : IUnique
    { 
        public ulong ID { get; set; }
        public string Name { get; set; }
    }
}

因为IList时泛型接口,而右边的List是泛型类,泛型类实现了泛型接口

带有一个类型参数的IList泛型接口,带有一个类型参数的List泛型类

C#的List就是ArrayList 长度可以改变,动态数组

运行结果:打印出来0-99

泛型接口IList用整型特化下,List泛型类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            IList list = new List();
            for (int i = 0; i < 100; i++)
            { 
                list.Add(i);
            }

            foreach (int item in list)
            { 
                Console.WriteLine(item);
            }
            Console.ReadLine();

        }
    }
}

类型参数为T,实现了IList泛型基接口、ICollection泛型基接口、IEnumerable泛型基接口……

List一定是可以被迭代的,因为实现了IEnumerable泛型基接口

ICollection泛型基接口——集合,可以往集合中增加新元素和删除元素

C#入门级——泛型、泛型类、泛型接口、泛型方法和泛型委托_第3张图片

很多泛型类型带不止一个类型参数,如:IDictionary泛型接口

举例:IDictionary泛型接口

int类型特化TKey类型  string类型特化TValue类型

使用特化后的IDictionary接口类型变量 引用 特化后的Dictionary类型实例

多态:IDictionary接口类型的变量dict可以引用一个Dictionary类型的实例,Dictionary泛型类实现了IDictionary接口,类型参数都是TKey TValue

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            IDictionary dict = new Dictionary();
            dict[1] = "Jack";
            dict[2] = "Mary";
            Console.WriteLine($"Student #1 is{dict[1]}");
            Console.WriteLine($"Student #2 is{dict[2]}");
            Console.ReadKey();

        }
    }
}

泛型方法

举例:两个整型数组合并一起

不使用泛型方法时,会出现以下情况:

成员膨胀

(方法也是类的成员)

更加容易出问题,两个方法都是静态的,类的静态成员,两个重载方法,除了类型不同以外,其他的逻辑都是相同的,万一修bug只修了其中一个方法,另一个方法忘记了就出问题了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] a1 = { 1, 2, 3, 4, 5 };
            int[] a2 = { 1, 2, 3, 4, 5, 6 };
            double[] a3 = { 1.1, 2.2, 3.3, 4.4, 5.5 };
            double[] a4 = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 };
            var result = Zip(a1, a2);
            Console.WriteLine(string.Join(",",result));
            Console.ReadKey();
        }

        static int[] Zip(int[] a, int[] b)
        {
            int[] zipped = new int[a.Length + b.Length];
            int ai = 0, bi = 0, 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 double[] Zip(double[] a, double[] b)
        {
            double[] zipped = new double[a.Length + b.Length];
            int ai = 0, bi = 0, 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;
        }
    }

}

使用泛型

方法后面加

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[] a1 = { 1, 2, 3, 4, 5 };
            int[] a2 = { 1, 2, 3, 4, 5, 6 };
            double[] a3 = { 1.1, 2.2, 3.3, 4.4, 5.5 };
            double[] a4 = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6 };
            var result = Zip(a1, a2);    //可以不写Zip(a1, a2);
            Console.WriteLine(string.Join(",",result));
            Console.ReadKey();
        }

        static T[] Zip(T[] a, T[] b)
        {
            T[] zipped = new T[a.Length + b.Length];
            int ai = 0, bi = 0, 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;
        }
    }

}

可以无需显式写 泛型方法在调用时类型参数自动推断

var result = Zip(a1,a2);   var result = Zip(a1,a2);

泛型委托

Action委托——只能引用没有返回值的方法

静态方法Say/Mul,没有返回值

使用泛型委托分别引用参数类型完全不同的方法

类型参数:告诉Action委托未来要引用的方法的参数类型是什么,有多少个参数

Action委托引用Say方法,Say方法只有一个String类型参数

通过委托去调用一个方法叫间接调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Action a1 = Say;
            a1.Invoke("Jack");

            Console.ReadKey();
        }

        static void Say(string str)
        { 
            Console.WriteLine($"Hello,{str}!");
        }
        static void Mul(int x)
        { 
            Console.WriteLine(x * 100);
        }
    }

}

直接像一个方法一样调用,委托本身就是一种可调用的类型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Action a1 = Say;
            a1("Jack");

            Console.ReadKey();
        }

        static void Say(string str)
        { 
            Console.WriteLine($"Hello,{str}!");
        }
        static void Mul(int x)
        { 
            Console.WriteLine(x * 100);
        }
    }

}

创建泛型委托实例,引用Mul函数,有一个int类型参数

调用a2委托,间接调用Mul方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Action a1 = Say;
            a1("Jack");
            Action a2 = Mul;
            a2(1);
            Console.ReadKey();
        }

        static void Say(string str)
        { 
            Console.WriteLine($"Hello,{str}!");
        }
        static void Mul(int x)
        { 
            Console.WriteLine(x * 100);
        }
    }

}

Func泛型委托——要有返回值

Func<类型参数:引用的方法有多少个参数及参数类型,最后一个类型参数:函数返回值类型>

特化Func泛型委托

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Func func1 = Add;
            var result = func1(100.1, 200.2);
            Console.WriteLine(result);
            Console.ReadKey();
        }

        static double Add(double a,double b)
        { 
            return a + b;
        }
    }
}

泛型委托和Lambda表达式的配合使用

对于逻辑简单的方法,不去声明,随调用去声明,匿名声明

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Func func1 = (double a, double b) => { return a + b; };
            var result = func1(100.1, 200.2);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

可以再简化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Func func1 = (a, b) => { return a + b; };
            var result = func1(100.1, 200.2);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

你可能感兴趣的:(C#,c#)