記錄C#語法的使用
記錄一下C#的用法
C# 6 的三個新的表示式
介紹 C# 6 的三個新語法:nameof 表示式、字串插值、和 null 條件運算子。
- nameof 表示式
C# 6 新增的 nameof 關鍵字可用來取得某變數的名稱。請看底下這個簡單範例,便能了解其作用:
1 | string firstName = "Joey"; |
比如說,為了防錯,我們經常在函式中預先檢查參數值是否合法,並將不合法的參數透過拋異常(exception)的方式通知呼叫端(或者寫入 log 檔案以供將來診斷問題)。像這樣:
1 | void LoadProduct(string productId) |
字串插值
NET Framework 提供的字串格式化方法 String.Format(…) 是一種對號入座的寫法,相當好用。
現在,C# 6 提供了另一種格式化字串的寫法,名曰「字串插值」(string interpolation)。
$”{變數名稱:格式規範}”1
2
3
4
5
6
7
8string firstName = "Michael";
string lastName = "Tsai";
int salary = 22000;
string msg1 = String.Format("{0} {1} 的月薪是 {2:C0}", firstName, lastName, salary);
string msg2 = $"{firstName} {lastName} 的月薪是 {salary :C0}";
Console.WriteLine(msg1);
Console.WriteLine(msg2);Null 條件運算子
保險起見,在需要存取某物件的屬性之前,我們通常會先檢查該物件是否為 null1
2
3
4
5
6
7
8
9
10
11
12static void NullPropagationDemo(string s)
{
if (s?.Length == 4) // 只有當 s 不為空時才存取它的 Length 屬性。
{
// Do something.
}
}
int? length = productList?.Length; // 若 productList 是 null,則 length 也是 null。
Customer obj = productList?[0]; // 若 productList 是 null,則 obj 也是 null。
int length = productList?.Length ?? 0; // 若 productList 是 null,則 length 是 0。
string name = productList?[0].FullName; // 若 productList 是 null,則 name 是 null。
有關json的用法
字串轉json物件,json物件轉字串
1 | public static void strJson() |
分組的用法
過去面對這種問題,我慣用的做法先定義一個Dictionary<string, List
foreach + Dictionary寫法用了好幾年,前幾天才忽然想到,這不就是SQL語法中的GROUP BY嗎?加上LINQ有ToDictionary, GroupBy(o => o.客戶編號).ToDictionary(o => o.Key, o => o.ToList()) 一行就搞定了呀!阿呆。
1 | using System; |