继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

c# 6.0新特性

慕用4979188
关注TA
已关注
手记 266
粉丝 63
获赞 531

写在前面

上篇文章介绍了c#6.0的using static,Auto Property Initializers,Index Initializers新的特性,这篇文章将把剩下的几个学习一下。

上篇文章:c#6.0新特性(一)

String Interpolation

为了拼接字符串,我们通常会使用String.Format通过索引并对索引进行赋值来完成。当然,有时这种做法在有多个参数的时候有点麻烦,在c#6.0中,有一种新特性,可以不再使用索引就实现我们的目的。你可以通过以$ sign开始指定一个参数。下面的例子,通过first name和last name获取full name。在这里,我们使用string.format并且为指定的索引指定值。

Before c#6.0

复制代码

using System;using System.Collections.Generic;namespace CplusplusNewFeature{    public class Program    {        static void Main(string[] args)        {            string firstName = "Mukesh";            string lastName = "Kumar";            Console.WriteLine("The Full Name of Employee " + string.Format("{0} {1}", firstName, lastName));            Console.ReadLine();        }    }}

复制代码

在c# 6.0中

我们不必像c#6.0之前那样做了,我们只需在字符串前通过$符号标记该字符串,c#6.0就知道在该字符串遇到{}中的内容,将使用我们定义变量进行替换。看一个例子:

复制代码

using System;using System.Collections.Generic;using static System.Console;namespace CplusplusNewFeature{    public class Program    {        static void Main(string[] args)        {            string firstName = "Mukesh";            string lastName = "Kumar";            WriteLine($"The Full Name of Employee {firstName} {lastName}");            ReadLine();        }    }}

复制代码

The Full Name of Employee Mukesh Kumar

在这里{}内的内容也相当于占位符,只不过这里需要你使用你需要替换的变量名称进行占位。

Expression Bodied Members

 lambda表达式在linq查询中是非常有帮助的。但在c#6.0中,你可以在属性和方法中使用lambda表达式提升你的效率,写更简洁的代码。

通过lambda表达式你可以使用一行代码定义一个方法(只针对简单短小逻辑的方法或者属性)。我相信,当你在大的应用程序中,将使用expression bodied members来获取基于条件的值。我们会直接创建一个方法,并在输出参数中返回他们的值。

在c#6.0之前

之前我们创建一个单独的方法去完成一些简单的任务。它可能是一行或者更多行代码。但是它是非常复杂和花费时间的。看一下下面的例子,有这样的两个方法GetFullName和AddTowNumber,它们只是拼接字符串和加两个数字。但是为了完成这一的任务,我们需要定义两个单独的方法。

复制代码

using System;using System.Collections.Generic;namespace CplusplusNewFeature{    public class Program    {        public static string GetFullName(string firstName, string lastName)        {            return string.Format("{0} {1}", firstName, lastName);        }        public static int AddTwoNumber(int firstNumber, int secondNumber)        {            return firstNumber + secondNumber;        }        static void Main(string[] args)        {            string firstName = "Mukesh";            string lastName = "Kumar";            int firstNumber = 10;            int secondNumber = 20;            Console.WriteLine(GetFullName(firstName, lastName));            Console.WriteLine(AddTwoNumber(firstNumber, secondNumber));            Console.ReadLine();        }    }}

复制代码

在c#6.0中

在c#6.0中,我们可以在定义的时候完成这样的任务,不再需要定义单独的方法去做这样的事情了。

复制代码

using System;using System.Collections.Generic;using static System.Console;namespace CplusplusNewFeature{    public class Program    {        public static string GetFullName(string firstName, string lastName) => firstName + " " + lastName;        public static int AddTwoNumber(int firstNumber, int secondNumber) => firstNumber + secondNumber;        static void Main(string[] args)        {            string firstName = "Mukesh";            string lastName = "Kumar";            int firstNumber = 10;            int secondNumber = 20;            WriteLine(GetFullName(firstName, lastName));            WriteLine(AddTwoNumber(firstNumber, secondNumber));            ReadLine();        }    }}

复制代码

Getter only Auto Properties

 在你使用属性的时候,getter和setter都是需要定义的。但是在c# 6.0中,你可以只定义属性的gtter方法。在c#6.0之前,当创建属性的时候,getter和setter是需要定义的。有时,我们并不需要创建setter,但是我们必须去定义它。但在c#6.0中,不再有这样的限制去编写这样的代码,你只需定义制度的属性即可。

看一下下面的例子,fistname和lastname在只有getter的情况下,为他们赋值。

In C#6.0

复制代码

using System;using System.Collections.Generic;namespace CplusplusNewFeature{    public class Program    {        string FirstName { get; } = "Mukesh";        string LastName { get; } = "Kumar";        public string FullName = string.Empty;        public Program()        {            FullName = FirstName + " " + LastName;        }        static void Main(string[] args)        {            Program prog = new Program();            Console.WriteLine("The Full Name is " + prog.FullName);            Console.ReadLine();        }    }}

复制代码

在一些反编译工具中,你会发现,你定义的只读属性,会在构造函数中为他们赋值。如果你在声明变量的时候为他们赋值了,实际发生赋值的是在他们的构造函数中。

看一个例子

public class TestClass{    public string TestProperty { get; } = "Test Property";     public readonly string TestField = "Test Field";}

用反编译工具进行查看,是在默认的构造函数中为他们赋值的。

public TestClass(){    this.<TestProperty>k__BackingField = "Test Property";    this.TestField = "Test Field";}

Exception Filters

 在引入Roslyn编辑器,这个特性也加入了vb中了。过滤器被用在基于一些条件参数的catch块中。通常,我们需要在一个catch苦熬中需要不同的条件抛出不同的异常类型。

但是在c#6.0中,你可以在每一个条件中校验信息并抛出他们的异常信息。

c#6.0之前

复制代码

using System;using System.Collections.Generic;namespace CplusplusNewFeature{    public class Program    {        static void Main(string[] args)        {            int errorCode = 404;            try            {                throw new Exception(errorCode.ToString());            }            catch (Exception ex)            {                if (ex.Message.Equals("404"))                    Console.WriteLine("This is Http Error");                else if (ex.Message.Equals("401"))                    Console.WriteLine("This is Unathorized Error");                else                    Console.WriteLine("This is some different exception");                Console.ReadLine();            }        }    }}

复制代码

在c#6.0中

通过c#6.0中,我们可以为不同的异常信息指定不同的抛出条件。看一个例子

复制代码

using System;using System.Collections.Generic;using static System.Console;namespace CplusplusNewFeature{    public class Program    {        static void Main(string[] args)        {            int errorCode = 404;            try            {                throw new Exception(errorCode.ToString());            }            catch (Exception ex) when (ex.Message.Equals("404"))            {                WriteLine("This is Http Error");            }            catch (Exception ex) when (ex.Message.Equals("401"))            {                WriteLine("This is Unathorized Error");            }            catch (Exception ex) when (ex.Message.Equals("403"))            {                WriteLine("Forbidden");            }            ReadLine();        }    }}

复制代码

Null Conditional Operators

在编码时,我们通常校验null,我们检验对象是否为null,并且尝试组织抛出NullReferenceExpression。但是为了这样做,为了达到这一的目的,我们需要编写额外的很长的代码。

但在c#6.0中,你可以通过null条件操作符question mark[?]完成这一的操作。

在c#6.0之前

复制代码

using System;using System.Collections.Generic;using System.Linq;namespace CplusplusNewFeature{    public class Program    {        static void Main(string[] args)        {            List<Employee> employees = new List<Employee>();            Program prog = new Program();            if (employees.FirstOrDefault() != null)            {                //This code will not hit because of employees is null;                Console.WriteLine(employees.First().Name);            }            else            {                Employee emp = new Employee();                emp.EmployeeId = 10;                emp.Name = "Mukesh Kumar";                emp.Address = "New Delhi";                employees.Add(emp);                Console.WriteLine(employees.First().Name);            }            Console.ReadLine();        }    }    public class Employee    {        public int EmployeeId { get; set; }        public string Name { get; set; }        public string Address { get; set; }    }}

复制代码

在c#6.0中

复制代码

using System;using System.Collections.Generic;using System.Linq;using static System.Console;using static System.Console;namespace CplusplusNewFeature{    public class Program    {        static void Main(string[] args)        {            List<Employee> employees = new List<Employee>();            Program prog = new Program();            //No need to check null in if condition            //null operator ? will check and return null if value is not there            WriteLine(employees.FirstOrDefault()?.Name);            //set the default value if value is null            WriteLine(employees.FirstOrDefault()?.Name ?? "My Value");            ReadLine();        }    }    public class Employee    {        public int EmployeeId { get; set; }        public string Name { get; set; }        public string Address { get; set; }    }}

复制代码

Declaration Expressions

使用这个特性,我们需要在表达式内部生命本地全局的变量。但是变量的作用域只在定义的块中。

c#6.0之前

复制代码

using System;using System.Collections.Generic;using System.Linq;namespace CplusplusNewFeature{    public class Program    {        static void Main(string[] args)        {            int myValue = 10;            if (int.TryParse("20", out myValue))            {                Console.WriteLine(myValue);                Console.ReadLine();            }        }    }}

复制代码

In Preview C# 6.0  [Features is not added with C# 6.0 Final Version, it might be come with C# 7.0]

复制代码

using System;using System.Collections.Generic;using System.Linq;using static System.Console;namespace CplusplusNewFeature{    public class Program    {        static void Main(string[] args)        {            if (int.TryParse("20", out var result))            {                return result;            }            return 0; // result is out of scope            // A new feature in C# 6.0 allows to declare variable inside TryParse method.            //Declaration expressions was cut from C# 6.0 and wasn't shipped in the final release.             //You currently can't do that. There is a proposal for it on GitHub for C# 7.        }    }

复制代码

总结

最后,我们已经学习了c#6.0的一些新特性,这些特性将改变我们编码效率。它将使我们的编码更简单,并且可以提供简单的途径去完成复杂的事情。

这也是年前最后一篇文章了,提前祝大家2016年春节快乐。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP