写在前面

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

原文地址:http://www.codeproject.com/Articles/1070659/All-About-Csharp-New-Features

上篇文章: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 = ;
int secondNumber = ; 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 = ;
int secondNumber = ; 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 = ;
try
{
throw new Exception(errorCode.ToString());
}
catch (Exception ex)
{
if (ex.Message.Equals(""))
Console.WriteLine("This is Http Error");
else if (ex.Message.Equals(""))
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 = ;
try
{
throw new Exception(errorCode.ToString());
}
catch (Exception ex) when (ex.Message.Equals(""))
{
WriteLine("This is Http Error");
}
catch (Exception ex) when (ex.Message.Equals(""))
{
WriteLine("This is Unathorized Error");
}
catch (Exception ex) when (ex.Message.Equals(""))
{
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 = ;
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 = ;
if (int.TryParse("", 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("", out var result))
{
return result;
}
return ; // 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年春节快乐。

最新文章

  1. css3的基本样式
  2. 【转】java架构师之路:JAVA程序员必看的15本书的电子版下载地址
  3. 博文写作——摘要&amp;摘要图标
  4. php面向对象加载类、常用设计模式
  5. datatables设置解析
  6. poi中getPhysicalNumberOfRows()和getLastRowNum()区别
  7. 38.Android之ListView简单学习(一)
  8. 未能正确加载“Microsoft.VisualStudio.Editor.Implementation.EditorPackage,
  9. Eclipse开发JavaWeb程序报Server Tomcat v7.0 at localhost was unable to start
  10. redis初试牛刀
  11. MySQL 5.5: InnoDB Change Buffering
  12. 小米2s 降到1299
  13. SQL 恢复master数据库方法,没有log文件的数据库文件恢复方法
  14. Oracle 数据库(oracle Database)Select 多表关联查询方式
  15. Knockout 系列
  16. Java线程:线程状态
  17. 【集美大学1411_助教博客】团队作业8——第二次项目冲刺(Beta阶段)
  18. Vagrant下共享目录下静态文件(js/jpg/png等)修改完运行报错
  19. python JoinableQueue在生产者消费者项目中的简单应用
  20. Python 常用系统模块整理

热门文章

  1. hdu 1003 Max sum(简单DP)
  2. ls文件与目录检视,文件内容查阅
  3. 使用DateLocaleConverter和SimpleDateFormat实现字符串转换成日期
  4. SDRAM总结
  5. ant+jenkins+testng+selenium集成环境搭建
  6. Mybatis框架_part1
  7. HDU 2298 Toxophily 【二分+三分】
  8. C++基础笔记(四)C++内存管理
  9. kvm虚拟机日常管理和配置操作命令梳理
  10. [资料]Keychain 获取设备唯一