C# 6.0 加入了不少东西,C# 的 语言风格变得更好了,周末忙了一上午做了一个demo. 直接代码上来

完整代码:

#define ASYNC
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using static System.Math;
namespace NewCharp6
{class Program{static void Main(string[] args){//Initilizers for auto properties and function with lambdavar salesOrder = new SalesOrder();Console.WriteLine("Begin to Test New In C# 6.0");Console.WriteLine("=====================Auto Init Property  lambda In A class=======================");Console.WriteLine("OrderNo:" + salesOrder.OrderNo);Console.WriteLine("OrderCode:" + salesOrder.OrderCode);Console.WriteLine("OrderInfo:" + salesOrder.OrderInfo);Console.WriteLine("GetOrderInfo:" + salesOrder.GetOrderInfo());Console.WriteLine("=====================Test Null Conditional Operators=======================");Console.WriteLine("Here Will Output Null Value.............");SalesInovice salesInvoice = new SalesInovice();Console.WriteLine(salesInvoice.OrderList?[0].OrderNo);//sample OperatorConsole.WriteLine(salesInvoice.salesReturn?.returnCode);//sample Operator//Initializers the Orders And RetutnConsole.WriteLine("Here Will Output Actual Value After Initializer the Object.............");salesOrder.OrderNo = Guid.NewGuid();salesOrder.OrderCode = "OS0001";salesInvoice.OrderList = new List<SalesOrder>();salesInvoice.OrderList.Add(salesOrder);salesInvoice.salesReturn = new SalesReturn();salesInvoice.salesReturn.returnNo = Guid.NewGuid();salesInvoice.salesReturn.returnCode = "RT0001";Console.WriteLine(salesInvoice.OrderList?[0].OrderNo + ":" + salesInvoice.OrderList?[0].OrderCode);Console.WriteLine(salesInvoice.salesReturn?.returnNo + ":" + salesInvoice.salesReturn?.returnCode);//Index InitializersConsole.WriteLine("Initializer An Collections With Index .............");var returnDictionary = new Dictionary<int, SalesReturn>() { [0] = new SalesReturn() { returnNo = Guid.NewGuid(), returnCode = "RT001" }, [1] = new SalesReturn { returnNo = Guid.NewGuid(), returnCode = "RT002" } };Console.WriteLine("Here Will Output the Dictionary:" + returnDictionary[0]?.returnNo + returnDictionary[0]?.returnCode);var returnStrDictionary = new Dictionary<String, SalesReturn>() { ["One"] = new SalesReturn { returnNo = Guid.NewGuid(), returnCode = "RT001" }, ["Two"] = new SalesReturn { returnNo = Guid.NewGuid(), returnCode = "RT002" } };Console.WriteLine("Here Will Output the Dictionary:" + returnStrDictionary["One"]?.returnNo + returnStrDictionary["One"]?.returnCode);//Here Will Output All Object in the Dictionarys foreach (KeyValuePair<string, SalesReturn> item in returnStrDictionary){Console.WriteLine("Key:" + item.Key + string.Format("   {0}-{1}", item.Value.returnNo, item.Value.returnCode));}//Here will Output the math function Directly Before we Will use System.Math.abs But Now Just use abs Console.WriteLine("=====================Using static NameSpace=======================");Console.WriteLine("using static System.Math at the head firse");Console.WriteLine("Output the abs value:" + Abs(-7));//Exception Filter In C# 6.0#if ASPNETConsole.WriteLine("=====================Exception Filter In C# 6.0=======================");try{try{Console.WriteLine("begin to throw ASPNET EXCEPTION.........");throw new ExceptionHander("ASP.Net Exception");}catch (ExceptionHander ex) when (ExceptionHander.CheckEx(ex)){//ASPNET EXCEPTION WILL NOT CATCH HEREConsole.WriteLine("Exception Type:" + ex.Message + "Was Catch the Other was Missing .......");}}catch (ExceptionHander ex){//ASPNET EXCEPTION WILL CATCH HEREConsole.WriteLine(ex.Message);}
#elif DATABASEtry{try{Console.WriteLine("begin to throw DATABASE EXCEPTION.........");throw new ExceptionHander((int)ExType.DATABASE, "DataBase Exception");}catch (ExceptionHander ex) when (ExceptionHander.CheckEx(ex)){Console.WriteLine("Exception Type:" + ex.Message + "Was Catch the Other was Missing .......");}}catch (ExceptionHander ex){//DATABASE EXCEPTION WILL CATCH HEREConsole.WriteLine(ex.Message);}#elif ASYNCConsole.WriteLine("========Begin To Test async in catch and finally blocks(C#6.0 Only)===============");try{throw new Exception("Error Occur");}catch (Exception ex){//TODO can't use the async In Mian // var returnAsync = await ProcessWrite(ex.Message);}
#endifConsole.ReadKey();}protected static SalesOrder GetSales(){SalesOrder salesOrder = new SalesOrder();salesOrder.OrderCode = "SO001";return salesOrder;}//async read and writepublic async void ProcessWrite(string text){string filePath = System.Environment.CurrentDirectory + "commonLog.txt";await WriteTextAsync(filePath, text);}private async Task WriteTextAsync(string filePath, string text){byte[] encodedText = Encoding.Unicode.GetBytes(text);using (FileStream sourceStream = new FileStream(filePath,FileMode.Append, FileAccess.Write, FileShare.None,bufferSize: 4096, useAsync: true)){await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);};}public async void ProcessRead(){string filePath = @"temp2.txt";if (File.Exists(filePath) == false){Debug.WriteLine("file not found: " + filePath);}else{try{string text = await ReadTextAsync(filePath);Debug.WriteLine(text);}catch (Exception ex){Debug.WriteLine(ex.Message);}}}private async Task<string> ReadTextAsync(string filePath){using (FileStream sourceStream = new FileStream(filePath,FileMode.Open, FileAccess.Read, FileShare.Read,bufferSize: 4096, useAsync: true)){StringBuilder sb = new StringBuilder();byte[] buffer = new byte[0x1000];int numRead;while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0){string text = Encoding.Unicode.GetString(buffer, 0, numRead);sb.Append(text);}return sb.ToString();}}}public class SalesOrder{public Guid OrderNo { get; set; } = new Guid();public String OrderCode { get; set; }public Int32 Quanlity { get; set; }public double UnitPrice { get; set; }public String OrderInfo => string.Format("lambda to property demo {0}:{1}", OrderNo, OrderCode);//lambda for properyies public String GetOrderInfo() => string.Format("lambda to function demo {0}:{1}", OrderNo, OrderCode);//lambda for functions }public class SalesInovice{public Guid InvoiceNo { get; set; }public String InvoiceCode { get; set; }public List<SalesOrder> OrderList { get; set; }public SalesReturn salesReturn { get; set; }}public class SalesReturn{public Guid returnNo { get; set; }public String returnCode { get; set; }}public class ExceptionHander : Exception{public int TypeofException { get; set; } = (int)ExType.ASPNET;public string Msg { get; set; }public ExceptionHander(int Type, string Message) : this(Message){TypeofException = Type;}public ExceptionHander(String msg){Msg = msg;}public static Boolean CheckEx(ExceptionHander ex){if (ex.TypeofException.Equals(ExType.DATABASE)){return true;}else{return false;}}}public enum ExType{DATABASE = 0,ASPNET = 1}
}

  

代码解读:

一.属性,方法的 lambda 表示法.

   public class SalesOrder{public Guid OrderNo { get; set; } = new Guid();public String OrderCode { get; set; }public Int32 Quanlity { get; set; }public double UnitPrice { get; set; }public String OrderInfo => string.Format("lambda to property demo {0}:{1}", OrderNo, OrderCode);//lambda for properyies public String GetOrderInfo() => string.Format("lambda to function demo {0}:{1}", OrderNo, OrderCode);//lambda for functions }

二.空值判断 更加简洁

 Console.WriteLine(salesInvoice.OrderList?[0].OrderNo + ":" + salesInvoice.OrderList?[0].OrderCode);
Console.WriteLine(salesInvoice.salesReturn?.returnNo + ":" + salesInvoice.salesReturn?.returnCode);

  

三. 集合根据index 初始化

  Console.WriteLine("Initializer An Collections With Index .............");var returnDictionary = new Dictionary<int, SalesReturn>() { [0] = new SalesReturn() { returnNo = Guid.NewGuid(), returnCode = "RT001" }, [1] = new SalesReturn { returnNo = Guid.NewGuid(), returnCode = "RT002" } };Console.WriteLine("Here Will Output the Dictionary:" + returnDictionary[0]?.returnNo + returnDictionary[0]?.returnCode);

  

四. 支持异常过滤 用 在catch 后用when关键字

  try{try{Console.WriteLine("begin to throw DATABASE EXCEPTION.........");throw new ExceptionHander((int)ExType.DATABASE, "DataBase Exception");}catch (ExceptionHander ex) when (ExceptionHander.CheckEx(ex)){Console.WriteLine("Exception Type:" + ex.Message + "Was Catch the Other was Missing .......");}}catch (ExceptionHander ex){//DATABASE EXCEPTION WILL CATCH HEREConsole.WriteLine(ex.Message);}

五.支持在catch 和 finally 上使用 异步方法

GitHub Code 下载: https://github.com/ShenZhenMS/NewFeatureCSharp6.git

参考博客: http://www.cnblogs.com/henryzhu/p/new-feature-in-csharp-6.html

希望对大家有帮助.

转载于:https://www.cnblogs.com/QuickTechnology/p/5635155.html

C# 6.0 新特性相关推荐

  1. JDK5.0新特性系列---目录

    JDK5.0新特性系列---目录 JDK5.0新特性系列---1.自动装箱和拆箱 JDK5.0新特性系列---2.新的for循环 JDK5.0新特性系列---3.枚举类型 JDK5.0新特性系列--- ...

  2. [转]C# 2.0新特性与C# 3.5新特性

    C# 2.0新特性与C# 3.5新特性 一.C# 2.0 新特性: 1.泛型List<MyObject> obj_list=new List(); obj_list.Add(new MyO ...

  3. Servlet 3.0 新特性概述

    Servlet 3.0 新特性概述 Servlet 3.0 作为 Java EE 6 规范体系中一员,随着 Java EE 6 规范一起发布.该版本在前一版本(Servlet 2.5)的基础上提供了若 ...

  4. Redis 6.0 新特性-多线程连环13问!

    来自:码大叔 导读:支持多线程的Redis6.0版本于2020-05-02终于发布了,为什么Redis忽然要支持多线程?如何开启多线程?开启后性能提升效果如何?线程数量该如何设置?开启多线程后会不会有 ...

  5. WCF4.0新特性体验(3):标准终结点(Standard Endpoints)

    今天在WCF4.0新特性体验第3节,我们介绍WCF4.0里的标准终结点概念,也就是Standard Endpoints. WCF4.0提供了那些标准终结点?他们有什么作用?如何使用标准终结点?如何该表 ...

  6. Servlet 2.0 Servlet 3.0 新特性

    概念:透传. Callback 在异步线程中是如何使用的.?? Servlet 2.0 && Servlet 3.0 新特性 Servlet 2.0 && Servle ...

  7. C#6.0,C#7.0新特性

    C#6.0,C#7.0新特性 C#6.0新特性 Auto-Property enhancements(自动属性增强) Read-only auto-properties (真正的只读属性) Auto- ...

  8. WCF4.0新特性体验(6):路由服务Routing Service(下)

    紧接前文WCF4.0新特性体验(5):路由服务Routing Service(上).今天我们介绍WCF4.0消息路由的实现机制,然后会讲解路由服务的实现过程. [4]WCF与路由服务: 其实在介绍WC ...

  9. 【收藏】C# 2.03.0新特性总结

    c#2.0新特性 范型 我们知道通用的数据结构可以采用object存储任何数据类型.使用object问题是: 显示的强制转带来的代码复杂性 换装箱拆箱的性能损失(为什么有性能损失?因为涉及动态内存分配 ...

  10. 返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API

    返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API 原文:返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 ...

最新文章

  1. 手把手教你用anaconda安装pytorch最新版
  2. 算法——遗传算法基础
  3. 第五章 Python函数你知多少
  4. [LAMP]Apache和PHP的结合
  5. 中国已经过了做手机操作系统的窗口期
  6. 计算机网络总结:第三章 运输层
  7. 考研英语作文:一封欢迎词
  8. Qt入门——三个臭皮匠顶个诸葛亮
  9. AI 名校课程书籍 需要学习
  10. (38)FPGA原语设计(BUFH)
  11. OpenShift 4 - 使用教程和免费试用环境
  12. mysql三高讲解(二):2.2 B+树的B的意义
  13. 当FORM的ENCTYPE=quot;multipart/form-dataquot; 时request.getParameter()获取不到
  14. python串口数据分包_python TCP Socket的粘包和分包的处理详解
  15. LeetCode 416. 分割等和子集(动态规划)(0-1背包)
  16. Julia: LaTeX 符号
  17. C语言从入门到精通 ————1.初识C语言
  18. I18N和L10N测试工具
  19. linux内存扩展,linux 扩展内存
  20. 语言学句法分析树形图怎么画_树形图(句法)

热门文章

  1. c++类的成员函数作回调函数为啥要声明为static的
  2. 简记GAN网络的loss
  3. Suggestion: add 'tools:replace=android:value' to meta-data element at AndroidManifest.xml:25:5-2...
  4. 面向对象的Oracle用法
  5. Linux 字符集问题
  6. JAVA笔记 之 Thread线程
  7. 我的MVVM框架 v3教程——todos例子
  8. 追赶法求解三对角线性方程组的MATLAB程序
  9. IE发现新的零日攻击漏洞 用户可采取缓解措施
  10. 用Asp.Net c#写的采集小例子