C#笔记(五)--- 面向对象和字符串内插

virtual and abstract

在 virtual 方法,任何派生类都可以选择重新实现。 派生类使用 override 关键字定义新的实现。 通常将其称为“重写基类实现”。 virtual 关键字指定派生类可以重写此行为。 还可以声明 abstract 方法,让派生类必须在其中重写此行为。 基类不提供 abstract 方法的实现。

面向对象设计的例子,值得学习

https://docs.microsoft.com/zh-cn/dotnet/csharp/tutorials/intro-to-csharp/object-oriented-programming

字符串的几种内插方式

// 第一种: 内插字符串
var name = "Francis";
Console.WriteLine($"Hello, {name}. It's a pleasure to meet you!");
// 第2种: 包含不同的数据类型
// Note: 当表达式结果的类型不是字符串时,会按照以下方式将其解析为字符串:
// 如果内插表达式的计算结果为 null,则会使用一个空字符串("" 或 String.Empty)。
// 如果内插表达式的计算结果不是 null,通常会调用结果表达式的 ToString 方法。
var item = (Name: "eggplant", Price: 1.99m, perPackage: 3);
var date = DateTime.Now;
Console.WriteLine($"On {date}, the price of {item.Name} was {item.Price} per {item.perPackage} items.");
// Result: On 04/10/2021 16:26:58, the price of eggplant was 1.99 per 3 items.
// 第三种: 控制内插表达式的格式
// 可通过在内插表达式后接冒号(“:”)和格式字符串来指定格式字符串。 “d”是标准日期和时间格式字符串,表示短日期格式。 “C2”是标准数值格式字符串,用数字表示货币值(精确到小数点后两位)。
// 将 {date:d} 中的“d”更改为“t”(显示短时间格式)、“y”(显示年份和月份)和“yyyy”(显示四位数年份)。 将 {price:C2} 中的“C2”更改为“e”(用于指数计数法)和“F3”(使数值在小数点后保持三位数字)。
Console.WriteLine($"On {date:d}, the price of {item.Name} was {item.Price:C2} per {item.perPackage} items");
// 第四种: 控制结果字符串中包含的格式字符串的字段宽度和对齐方式
// -25: (负数)->左对齐,(正数)->右对齐, 数值->字段宽度
var inventory = new Dictionary<string, int>()
  {
      ["hammer, ball pein"] = 18,
      ["hammer, cross pein"] = 5,
      ["screwdriver, Phillips #2"] = 14
  };

  Console.WriteLine($"Inventory on {DateTime.Now:d}");
  Console.WriteLine(" ");
  Console.WriteLine($"|{"Item",-25}|{"Quantity",10}|");
  foreach (var item in inventory)
    Console.WriteLine($"|{item.Key,-25}|{item.Value,10}|");
/** result:
* Inventory on 04/10/2021
*  
* |Item                     |  Quantity|
* |hammer, ball pein        |        18|
* |hammer, cross pein       |         5|
* |screwdriver, Phillips #2 |        14|
*/

posted @ 2021-04-11 00:21  FrancisForeverhappy  阅读(94)  评论(0编辑  收藏  举报