本文列出個(gè)人感覺比較有用的幾個(gè)新功能,供大家參考,具體內(nèi)容如下
注意:這些新特性只能用于VS2015及更高版本,無(wú)法在VS2013、VS2010等低版本中使用。當(dāng)然,如果你不喜歡這些新的特性,仍然可以繼續(xù)使用原來(lái)的用法(所以說(shuō)它是新的語(yǔ)法糖)。
1、自動(dòng)屬性初始化的改進(jìn)(有用)
原來(lái)的用法(聲明時(shí)無(wú)法同時(shí)初始化),例如:
class MyClass{ public int Age { get; set; } public string Name { get; set; } public MyClass() { Age = 20; Name = "張三"; }} 新用法(聲明時(shí)可同時(shí)初始化,更方便了),例如:
class MyClass{ public int Age { get; set; } = 20; public string Name { get; set; } = "張三";} 2、String.Format的改進(jìn)(有用)
原來(lái)的用法:用string.Format(…)實(shí)現(xiàn),例如:
class MyClass{ public void MyMethod() { string name = "張三"; int age = 20; string s1 = string.Format("{0},{1}", name, age); string s2 = string.Format("姓名={0},年齡={1}", name, age); string s3 = string.Format("{0,15},{1:d3}", name, age); string s4 = string.Format("{0,15},{1,10:d3}", name, age); Console.WriteLine("{0},{1},{2},{3}", s1, s2, s3 ,s4); string s5 = string.Format("{0:yyyy-MM-dd}", DateTime.Now); }} 新用法:用“$”前綴實(shí)現(xiàn)(變量直接寫到大括號(hào)內(nèi),而且?guī)е悄芴崾荆奖懔耍纾?nbsp;
class MyClass{ public void MyMethod() { string name = "張三"; int age = 20; string s1 = $"{name},{age}"; string s2 = $"姓名={name},年齡={age}"; string s3 = $"{name,15},{age:d3}"; string s4 = $"{name,15},{age,10:d3}"; Console.WriteLine($"{s1},{s2},{s3},{s4}"); string s5 = $"{DateTime.Now:yyyy-MM-dd}"; }} 3、字典的初始化
原來(lái)的用法:
class MyClass{ public void MyMethod() { Dictionary<string, int> student = new Dictionary<string, int>(); student.Add("a1", 15); student.Add("a2", 14); student.Add("a3", 16); }} 新用法(可以直接寫初始化的值,更方便了):
class MyClass{ public void MyMethod() { Dictionary<string, int> student = new Dictionary<string, int>() { ["a1"] = 15, ["a2"] = 14, ["a3"] = 16 }; }} 4、可以用static聲明靜態(tài)類的引用
原來(lái)的用法:
using System;namespace MyApp{ class Demo1New { public static double MyMethod(double x, double angle) { return Math.Sin(x) + Math.Cos(angle); } }} 新用法(表達(dá)式比較復(fù)雜的時(shí)候有用,代碼更簡(jiǎn)潔了):
using static System.Math;namespace MyApp{ class Demo1New { public static double MyMethod(double x, double angle) { return Sin(x) + Cos(angle); } }}
新聞熱點(diǎn)
疑難解答
圖片精選