写在前面

上篇文章介绍了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. 《JavaScript修炼之道》读书笔记

    1.参考书目 入门:<JavaScript DOM编程艺术>第二版 进阶:<JavaScript高级程序设计>第二版.<JavaScript编程精粹> <Ja ...

  2. C/C++ 位域

    //假设硬件平台是intel x86(little endian) typedef unsigned int uint32_t; void inet_ntoa(uint32_t in) { ]; re ...

  3. 2.NopCommerce中文语言包

    由于NopCommerce是纯英语环境,给英语不好的管理人员带来诸多不便. NopCommerce支持多语言环境,所以我们只要安装中文语言包,让NopCommerce支持后台中文操作环境. 首先先下载 ...

  4. PHP采集程序中的常用函数

  5. Windows路由表详解

    对于路由器的路由表,大部分网管朋友都很熟悉,但是对于windows的路由表,可能了解的人就相对少一些.今天我们就一起来看看windows路由表.   一. windows路由表条目解释 1. 使用ip ...

  6. Debian系统网卡调试出问题,无线网卡提示device not managed如何解决?

    参考文章:<How to fix Wired Network interface “Device not managed” error in Debian or Kali Linux?> ...

  7. Lambda 表达式(C# 编程指南)

    Lambda 表达式是一种可用于创建委托或表达式目录树类型的匿名函数. 通过使用 lambda 表达式,可以写入可作为参数传递或作为函数调用值返回的本地函数.Lambda 表达式对于编写 LINQ 查 ...

  8. ArrayList和Hashtable

    public class Tools{ public string Name{get ;set;}} #region 0.1ArrayList集合 ////告诉内存,我要存储内容 //ArrayLis ...

  9. user database的initial size和dbcc shrinkfile

    之前我们讨论了dbcc shrinkfile改变tempdb initial size的情况.而用DBCC Shrinkfile去收缩一个user database,情况就比较简单了.让我们通过一些测 ...

  10. ESLint 检查代码质量

    利用 ESLint 检查代码质量 其实很早的时候就想尝试 ESLint 了,但是很多次都是玩了一下就觉得这东西巨复杂,一执行检查就是满屏的error,简直是不堪入目,遂放弃.直到某天终于下定决心深入看 ...