學習《深入理解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#》的相關知識。謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM