写在前面

上篇文章介绍了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年春节快乐。

c# 6.0新特性(二)的更多相关文章

  1. C# 6.0 新特性 (二)

    自动属性初始化表达式 有过正确实现结构经验的所有 .NET 开发人员无疑都为一个问题所困扰:需要使用多少语法才能使类型固定不变(为 .NET 标准建议的类型).此问题实际上是只读属性存在的问题: 定义 ...

  2. C++2.0新特性(二)——<一致性初始化、Initializer_list 、for循环、explicit>

    一.一致性初始化(uniform initialization) 之前初始化时存在多个版本,让使用者使用时比较混乱,现在提供一种万用的初始化方法,就是使用大括号. 原理解析:当编译器看到大括号包起来的 ...

  3. 浅谈Tuple之C#4.0新特性那些事儿你还记得多少?

    来源:微信公众号CodeL 今天给大家分享的内容基于前几天收到的一条留言信息,留言内容是这样的: 看了这位网友的留言相信有不少刚接触开发的童鞋们也会有同样的困惑,除了用新建类作为桥梁之外还有什么好的办 ...

  4. C#发展历程以及C#6.0新特性

    一.C#发展历程 下图是自己整理列出了C#每次重要更新的时间及增加的新特性,对于了解C#这些年的发展历程,对C#的认识更加全面,是有帮助的. 二.C#6.0新特性 1.字符串插值 (String In ...

  5. [转]Servlet 3.0 新特性详解

    原文地址:http://blog.csdn.net/xiazdong/article/details/7208316 Servlet 3.0 新特性概览 1.Servlet.Filter.Listen ...

  6. [C#]6.0新特性浅谈

    原文:[C#]6.0新特性浅谈 C#6.0出来也有很长一段时间了,虽然新的特性和语法趋于稳定,但是对于大多数程序猿来说,想在工作中用上C#6.0估计还得等上不短的一段时间.所以现在再来聊一聊新版本带来 ...

  7. 腾讯云安全:开发者必看|Android 8.0 新特性及开发指南

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 背景介绍 谷歌2017 I/O开发者大会今年将于5月17-19日在美国加州举办.大会将跟往年一样发布最新的 A ...

  8. Android Oreo 8.0 新特性实战 Autosizing TextView --自动缩放TextView

    Android Oreo 8.0 新特性实战 Autosizing TextView --自动缩放TextView 8.0出来很久了,这个新特性已经用了很久了,但是一直没有亲自去试试.这几天新的需求来 ...

  9. Django 2.0 新特性 抢先看!

    一.Python兼容性 Django 2.0支持Python3.4.3.5和3.6.Django官方强烈推荐每个系列的最新版本. 最重要的是Django 2.0不再支持Python2! Django ...

随机推荐

  1. hdu 3064 twoNumber

    twoNumber Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 2048/1024 K (Java/Others) Total Su ...

  2. HTTP详解1-工作原理

    1. HTTP简介 HTTP协议(HyperText Transfer Protocol,超文本传输协议)是用于从WWW服务器传输超文本到本地浏览器的传送协议.它可以使浏览器更加高效,使网络传输减少. ...

  3. Linux shell misc

    sometimes you will write shell in windows platform, be careful for this, adjust the notepad plus plu ...

  4. Hadoop_YARN框架

    Hadoop学习笔记总结 01. YARN框架 1. 新一代的框架介绍 YARN的职能就是将资源调度和任务调度分开.资源管理器ResourceManager全局管理所有应用程序计算资源的分配,每一个j ...

  5. Java : 使用jar包里的图片作为窗体的ICON

    文件结构: 源包- -/code/Jframe1.java -/image/1.png 目标: Jframe1.java 使用"/image/1.png"作为左上角的icon 核心 ...

  6. uva 120 stacks of flapjacks ——yhx

     Stacks of Flapjacks  Background Stacks and Queues are often considered the bread and butter of data ...

  7. selenium使用等待的几种方式

    1.使用java的sleep try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated c ...

  8. 深度优先搜索 codevs 1065 01字符串

    codevs 1065 01字符串  时间限制: 1 s  空间限制: 128000 KB  题目等级 : 黄金 Gold 题目描述 Description 输出仅有0和1组成的长度为n的字符串,并且 ...

  9. POJ 3150 Cellular Automaton --矩阵快速幂及优化

    题意:给一个环,环上有n块,每块有个值,每一次操作是对每个点,他的值变为原来与他距离不超过d的位置的和,问k(10^7)次操作后每块的值. 解法:一看就要化为矩阵来做,矩阵很好建立,大白书P157页有 ...

  10. TopCoder SRM 633 Div.2 500 Jumping

    题意:给一个点(x,y),给一些步长delta1,delta2...deltaN,问从(0,0)严格按照步长走完N步后能否正好到达(x,y)点. 解法:其实就是判断这些线段和(0,0)-(x,y)这条 ...