擴展自動屬性語法
自動屬性初始化表達式。
public class Example
{
// 6.0新增語法糖
public string FirstName { get; set; } = "Monkey";
// 6.0之前的寫法
//private string _firstName = "Monkey";
//public string FirstName
//{
// get { return _firstName; }
// set { _firstName = value; }
//}
public Example()
{
}
}
自動屬性可以不定義 set 訪問器。
public class Example
{
public string FirstName { get; } = "Monkey";
public string LastName { get; }
public Example()
{
}
}
只讀屬性可以在類型構造函數中初始化。
public class Example
{
public string FirstName { get; } = "Monkey";
public string LastName { get; }
public Example(string lastName)
{
LastName = lastName;
}
}
Null 條件運算符
用于在執行成員訪問 (?.) 或索引 (?[) 操作之前,測試是否存在 NULL。 可幫助編寫更少的代碼來處理 null 檢查。
成員訪問 (?.) :
public static string Truncate(string value, int length)
{
return value?.Substring(0, Math.Min(value.Length, length));
// C# 6.0 之前的寫法
//string result = value;
//if (value != null)
//{
// result = value.Substring(0, Math.Min(value.Length, length));
//}
//return result;
}
索引 (?[) 操作:
List<Example> examples = null;
Example example = examples?[0];
// 上述相當于 Example? item = (examples != null) ? examples[0] : null
Console.WriteLine(example == null); // 輸出 True
導入靜態類 (using static)
允許訪問類型的靜態成員,而無需限定使用類型名稱進行訪問:
//靜態導入Console
using static System.Console;
using static System.Math;
using static System.DayOfWeek;
class Program
{
static void Main()
{
//直接使用方法而不用Console.WriteLine
WriteLine(Sqrt(3*3 + 4*4));
WriteLine(Friday - Monday);
}
}
字符串格式化
// 字符串格式化可以這樣寫:
var s1 = $"{p.Name} is {p.Age} year{{s}} old";
var s2 = $"{p.Name,20} is {p.Age:D3} year{{s}} old";
var s3 = $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old";
nameof 表達式
WriteLine(nameof(DayOfWeek.Friday)); // 輸出 Friday
static void Main(string[] args)
{
throw new ArgumentNullException(nameof(args), "ArgumentNullException");
}
上面示例代碼運行結果:
未經處理的異常: System.ArgumentNullException: ArgumentNullException
參數名: ** args**
字典初始化器
static void Main(string[] args)
{
var strings = new Dictionary<string, string>()
{
["ABC"] = "abc",
["DEF"] = "def"
};
foreach (var s in strings)
{
WriteLine(s.Key + ": " + s.Value);
}
WriteLine();
var numbers = new Dictionary<int, string>
{
[7] = "seven",
[9] = "nine",
[13] = "thirteen"
};
foreach (var n in numbers)
{
WriteLine(n.Key + ": " + n.Value);
}
ReadKey();
}
上面示例代碼輸出結果為:
ABC: abc
DEF: def
7: seven
9: nine
13: thirteen
異常過濾器
catch (ArgumentNullException e) when (e.ParamName == “…”)
{
}
如果括號表達式(when)的結果為 true 時,才執行對應 catch 塊中的語句,否則繼續搜索處理程序。
static void Main(string[] args)
{
try
{
throw new ArgumentNullException(nameof(args), "ArgumentNullException");
}
catch (ArgumentNullException ex) when (ex.ParamName == "arges")
{
WriteLine("ArgumentNullException");
}
catch (Exception ex) when (ex.InnerException == null)
{
WriteLine("Exception");
}
}
示例代碼輸出結果為:
Exception
在 catch 和 finally 塊使用關鍵字 await
C# 6.0 之前catch和finally塊中是不能用 await 關鍵詞的。現在我們可以再這兩個地方使用await了。
public async void Info()
{
try
{
//Do something
}
catch (Exception)
{
await SumPageSizesAsync();
}
finally
{
await SumPageSizesAsync();
}
}
private async Task SumPageSizesAsync()
{
string url = "http://api.xxxx.com/";
HttpClient client = new HttpClient();
Task<byte[]> getContentsTask = client.GetByteArrayAsync(url);
byte[] urlContents = await getContentsTask;
}