您的位置:首页 > 编程语言 > C#

深入理解 c# 第一章 c#3 显示未知价格的产品

2018-04-02 16:30 357 查看
class DisplayProductsWithUnknownPrice
{
static void Main()
{
List<ProductWithNullablePrice> products = ProductWithNullablePrice.GetSampleProducts();
foreach (ProductWithNullablePrice product in products.Where(p => p.Price == null))
{
Console.WriteLine(product.Name);
}
}
}
跟 return p.Price == null 匿名方法 作用是一样的

public string Name { get; private set; }
public decimal? Price { get; private set; }? 表示可以将null 的值传过来,null含义 从“不指向任何对象的一个特殊引用”变成“没有给出其他数据的任意可空类型的一个特殊值
输入 public static List<ProductWithNullablePrice> GetSampleProducts()
{
return new List<ProductWithNullablePrice>
{
new ProductWithNullablePrice { Name="West Side Story", Price = 9.99m },
new ProductWithNullablePrice { Name="Assassins", Price=14.99m },
new ProductWithNullablePrice { Name="Frogs", Price=13.99m },
new ProductWithNullablePrice { Name="Sweeney Todd", Price=null}
};
}输出
Sweeney Todd

处理未知数据的方法
c#1 要么维护一个标志,要么更改引用类型的语义,要么利用一个魔数 就是自己知道意义 但其他人不知道意义的数
c#2 可空类型避免了 c#1 的各种繁琐方案 语法糖简化编程
c#3 可选参数简化 默认设置
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c#