zoukankan      html  css  js  c++  java
  • 学习《深入理解C#》—— 可空类型、可选参数和默认值 (第一章1.3)

    目录

    C# 可空类型

    在日常生活中,相信大家都离不开手机,低头族啊!哈哈。。。 假如手机厂商生产了一款新手机,暂时还未定价,在C#1中我们该怎么做呢?

    常见的解决方案:

    1. 围绕 decimal 创建一个引用类型包装器;
    2. 维护一个单独的 Boolean 标志,它表示价格是否已知;
    3. 使用一个“魔数”(magic value)(比如 decimal.MinValue )来表示未知价格。
     1   public class Product
     2     {
     3         private string name;
     4         private ProductPrice price;
     5 
     6         public Product(string name, ProductPrice price)
     7         {
     8             this.name = name;
     9             this.price = price;
    10         }
    11     }
    12     public class ProductPrice
    13     {
    14         public decimal Price;
    15         public bool HasPrice;
    16     }

     而在C#2引入可空类型,使事情得到了极大的简化。

     1 public class Product
     2     {
     3         public string Name { get; set; }
     4         public decimal? Price { get; set; }
     5         public Product(string name, decimal? price )
     6         {
     7             this.Name = name;
     8             this.Price = price;
     9         }    
    10     }

    C# 可选参数和默认值

    在我们日常的开发中,调用方法时对于特定参数总是会传递同样的值,而传统的解决方案是对方法的重载。  我们回到上一篇内容中讲到的Product类,假如我们的大多数产品不包含价格,而在C#4中引入了可选参数,来简化这类操作。

     1 public class Product
     2     {
     3         public string Name { get; set; }
     5         public decimal? Price { get; set; }
     7         public Product(string name, decimal? price = null)
     8         {
     9             this.Name = name;
    10             this.Price = price;
    11         }
    12         public static List<Product> GetSampleProducts()
    13         {
    14             List<Product> list = new List<Product>();
    15             list.Add(new Product("硬装芙蓉王"));
    16             list.Add(new Product("精白沙", 9m));
    17             list.Add(new Product("软白沙", 5.5m));
    18             return list;
    19         }
    20         public override string ToString()
    21         {
    22             return string.Format("{0}:{1}", Name, Price);
    23         }
    24     }

    备注:

    1. 声明的可选参数可指定一个常量值,不一定为null。 如上述代码中可将产品的价格默认为decimal? price = 1.2m等。
    2. 可选参数可以应用于任何类型的参数,但对于除字符串外的任意引用类型,只能使用null作为常量值。
    3. 当方法有可选参数并设定了默认值,调用此方法时可选参数可不传递参数,此时默认传递的是设定的默认值。 

    相关资料

          浅谈C#的可空类型

           C#可空类型

     这篇就写到这里。下篇我们将继续学习《深入理解C#》的相关知识。谢谢!

  • 相关阅读:
    ios程序中传值的几种方式
    iOS系统、设备信息获取方式
    关于如何使自定义的Button和系统的UIBarButtonItem保持一致的两种方法
    关于iOS中音视频播放的几种方式介绍
    关于IOS数据操作方式详解(三)— Sqlite数据解析
    关于iOS数据操作方式详解(二)— Jason数据解析
    关于IOS数据操作方式详解(一)— XML数据解析
    git常用命令
    pip及npm换源
    win10安装Docker并换国内源
  • 原文地址:https://www.cnblogs.com/liujie2272/p/6562130.html
Copyright © 2011-2022 走看看