博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# 6.0 新特性
阅读量:6591 次
发布时间:2019-06-24

本文共 10986 字,大约阅读时间需要 36 分钟。

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

完整代码:

#define ASYNCusing 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 lambda            var 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 Operator            Console.WriteLine(salesInvoice.salesReturn?.returnCode);//sample Operator            //Initializers the Orders And Retutn            Console.WriteLine("Here Will Output Actual Value After Initializer the Object.............");            salesOrder.OrderNo = Guid.NewGuid();            salesOrder.OrderCode = "OS0001";            salesInvoice.OrderList = new List
(); 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 Initializers Console.WriteLine("Initializer An Collections With Index ............."); var returnDictionary = new Dictionary
() { [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
() { ["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
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 ASPNET Console.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 HERE Console.WriteLine("Exception Type:" + ex.Message + "Was Catch the Other was Missing ......."); } } catch (ExceptionHander ex) {//ASPNET EXCEPTION WILL CATCH HERE Console.WriteLine(ex.Message); }#elif DATABASE 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 HERE Console.WriteLine(ex.Message); }#elif ASYNC Console.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); }#endif Console.ReadKey(); } protected static SalesOrder GetSales() { SalesOrder salesOrder = new SalesOrder(); salesOrder.OrderCode = "SO001"; return salesOrder; } //async read and write public 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
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
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
() { [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 HERE                Console.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

你可能感兴趣的文章
求js数组中最小值
查看>>
学习笔记之机器学习(Machine Learning)
查看>>
正确率、召回率和 F 值
查看>>
UVA10018 Reverse and Add
查看>>
nodejs实现简易MVC
查看>>
【转载】CocoaPods安装和使用教程
查看>>
Kettle提高输入输出数据总结
查看>>
7.16学习进度
查看>>
python之字符编码(三)
查看>>
前三次作业总结——分析与反思
查看>>
【BZOJ2117】 [2010国家集训队]Crash的旅游计划
查看>>
C++内存释放问题~
查看>>
安装ESXI 5.5卡在LSI_MR3.V00解决方案
查看>>
java反射
查看>>
自定义页面,组件加载
查看>>
UIimageView的contentmodel现实模式一看就懂
查看>>
C语言基础学习5:字符串与指针
查看>>
开源中国+soucetree
查看>>
jsp的九大内置对象和四大作用域
查看>>
新iPad未到 老iPad价格反弹
查看>>