本文共 2668 字,大约阅读时间需要 8 分钟。
C# 6.0中引入的新特性,以下是测试过的
1.自动的属性初始化器 Auto Property Initializer
////// C#6.0 自动属性不需要编写构造器就能添加初始值/// public class AutoPropertyInCsharp6{ public int PostID { get; } = 1; public string PostName { get; } = "Post1"; public string PostTitle { get; protected set; } = string.Empty; public AutoPropertyInCsharp6() { //实验证明,在构造器中PostID已经有了初始值 Console.WriteLine(PostID); }}
1.1 为访问器添加访问限制
public string FirstName { get; private set; }public string LastName { get; private set; }2. 字典初始化器 Dictionary Initializer
////// 字典类型数据初始化/// public class DictionaryInitializerInCSharp6{ ////// 之前的字典初始化器 /// public DictionaryList1 = new Dictionary () { { "name1","12"}, { "name2","13"}, }; /// /// C#6.0 增加的字典初始化器 /// public DictionaryList2 = new Dictionary () { ["name1"] = "12", ["name2"] = "13", };}
3. 静态的Using Static Using
//C#6.0 引用静态类的方式using static System.Console;namespace Grammar2._1{ public class StaticUsingInCSharp6 { public void Test1() { WriteLine("Static Using in C# 6"); } }}4.catch 块中的 await
///5.异常过滤器 Exception Filter/// 声明一个异步的方法/// public async void CatchTest(){ try { int a = Convert.ToInt32("a"); Console.WriteLine(a); } catch (Exception ex) { await doSomething(ex); }}private Task doSomething(Exception ex){ return Task.Run(() => { Console.WriteLine("doSomething:" + ex.Message); });}
///6.用于检查NULL值的条件访问操作符/// try/catch 语句when关键词过滤/// public void CacheTest2(){ try { int a = Convert.ToInt32("a"); Console.WriteLine(a); } catch (Exception ex) when (ex.InnerException == null) { Console.WriteLine("ex.InnerException为空"); }}
////// 用于检查null值得条件访问操作符 ?./// public void NullTest1(){ StaticUsingInCSharp6 auto1 = new StaticUsingInCSharp6(); // StaticUsingInCSharp6 auto1 = null; string str = null; str = auto1?.Str ?? "空字符串"; Console.WriteLine(str);}public string Str { get; set; } = "abc";
7.字符串插值处理
////// C# 6.0 字符串插值处理/// public class StringInterpolation{ public static string Test1() { string first = "san"; string send = "zhang"; string result = $"{send}--{first}"; Console.WriteLine(result); return result; } public static string FirstName { get; set; } = "san"; public static string SendName { get; set; } = "zhang"; public static string FullName => $"{FirstName}--{SendName}"; public static string GetAll() => $"Name:{FullName},Name2:{StringInterpolation.Test1()}";}
MSDN说明文档:
参考文件:
转载地址:http://gcogi.baihongyu.com/