C#控制台泛型简单举例

泛型的作用在于避免膨胀

打个比方 我是个苹果厂商

1.我卖苹果
2.苹果的属性是 颜色(红苹果,青苹果)

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

实例化苹果

Apple apple = new Apple{
     Color = "red"}


然后我有个盒子装苹果

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

然后就可以卖了

 static void Main(string[] args)
        {
     
            Apple apple = new Apple() {
      Color = "red" };
            Box box1 = new Box() {
      Apple = apple };
            Console.WriteLine(box1.Apple.Color);
            Console.ReadLine();
        }

规模扩大
开始卖书

 class Book
    {
     


        public string Name {
      get; set; }


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

业务扩大 口碑良好 种类增加
如果我想往杂货铺方向转变

现在问题来了

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

如果卖一千多种
每次卖都要增加删除种类
无穷无尽的代码会让人迷失自我

这个时候 泛型就来了

泛型改装了一下我的盒子

    class Box<TCargo>
    {
     

        public TCargo Cargo {
      get; set; }

    }

我傻了:你这样我怎么卖?
泛型:卖东西啦又不是卖盒子
我:东西给你你来卖
泛型:哦哦好的

 static void Main(string[] args)

        	{
     
 			Apple apple = new Apple() {
      Color = "red" };
            Book book = new Book() {
      Name = "HarryPotter" };
    		Box<Apple> box1 = new Box<Apple> {
      Cargo = apple };
            Box<Book> box2 = new Box<Book> {
      Cargo = book };

  



            Console.WriteLine(box1.Cargo.Color);
            Console.WriteLine(box2.Cargo.Name);
            }

我:牛!

泛型可以载入任何一个类并且重新实例化

你可能感兴趣的:(C#控制台泛型简单举例)