C#学习笔记(二十五)泛型

本文深入讲解泛型编程的概念,包括泛型类、接口、方法及委托的使用方式,并通过具体的代码示例阐述如何解决类型膨胀和成员膨胀问题。

泛型generic

在面向对象编程中,地位与接口相当。

什么是泛型?

泛泛而谈,数据类型,泛化数据类型。并非特指。特指的叫特化,叫具体化。泛化与特化相对。

泛型的东西,在编程时不能直接拿来使用,在使用之前,必须要经过具体化,也就是说特化。

 

泛型的正交性:

编程实体: 泛型 正交结果
Yes 泛型类
接口 Yes 泛型接口
委托 Yes 泛型委托
方法 Yes 泛型方法
属性 Yes 泛型属性
字段 Yes 泛型字段
。。。 Yes 。。。

泛型与其他编程实体都有正交点。


为什么需要泛型?

避免成员膨胀或者类型膨胀


举个泛型类栗子:

假设我是一个小商店的店主。一开始小商店非常小,我只卖苹果。用一个小盒子给用户包装起来。

class Program
{
    static void Main(string[] args)
    {
        Apple apple = new Apple(){Color = "Red"};
        Box box = new Box(){Cargo = apple};
        Console.WriteLine(box.Cargo.Color);
    }
}

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

class Box
{
    public Apple Cargo { get; set; }
}

随着时间的推移,商店越来越大,我开始卖书。也用一个盒子包装起来。

class Program
{
    static void Main(string[] args)
    {
        Apple apple = new Apple(){Color = "Red"};
        Box box = new Box(){Cargo = apple};
        Console.WriteLine(box.Cargo.Color);
    }
}

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

class Book
{
    public string Name { get; set; }
}

class Box
{
    public Apple Cargo { get; set; }
}

此时,book也需要用box。

有两种解决方案,一种是继续新建一个类:BookBox。并将苹果的盒子修改为AppleBox。

class Program
{
    static void Main(string[] args)
    {
        Apple apple = new Apple(){Color = "Red"};
        AppleBox box = new AppleBox(){Cargo = apple};
        Console.WriteLine(box.Cargo.Color);
        
        Book book = new Book(){Name = "New Book!"};
        BookBox bookBox = new BookBox(){Cargo = book};
        Console.WriteLine(bookBox.Cargo.Name);
    }
}

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

class Book
{
    public string Name { get; set; }
}

class AppleBox
{
    public Apple Cargo { get; set; }
}

class BookBox
{
    public Book Cargo { get; set; }
}

此时的问题:类型膨胀。如果商品持续增多,一千个商品,就需要有一千个类。那么需要准备的盒子也相应变多。此时我们的想法是准备一种盒子,然后盒子中有各种各样不同类型的属性

如此第二种解决方案:

class Program
{
    static void Main(string[] args)
    {
        Apple apple = new Apple(){Color = "Red"};
        Book book = new Book(){Name = "New Book!"};
        Box box1 = new Box
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值