写在前面

上篇文章介绍了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. Plus One

    Plus One https://leetcode.com/problems/plus-one/ Given a non-negative number represented as an array ...

  2. APP 接口开发及读取静态缓存

    <?php /** * Description: App 接口 * Create date:2015-10-19 13:36 * Author: zhaoyingnan **/ class Re ...

  3. Android监听键盘显示和隐藏

    问题概况:横板cocos2dx游戏,点击输入框弹出键盘时,界面要求跟随网上平易,不能挡住输入框.这种问题只出现在非全屏键盘到情况下. 方案1:mainActivity重写onconfiguration ...

  4. Icacls 在windows目录文件授权中的应用

    前言 最近因工作需要,需要对批量服务器某一目录下的文件进行统一授权,对于linux来说,授权很方便,对于window来说,要对目录下的文件进行批量授权还是很不方便的,windows平台授权自然想到用i ...

  5. WEB安全--Google Hacking

    通常我们用Google查询一些我们测试站点的一些信息,Google提供了一系列的搜索语句,下面我为大家详细的介绍一下! 常用语法: site:指定域名 intext:正文中存在关键字的网页 intit ...

  6. J2EE笔记2

    1. 部署并启动 tomcat 服务器.1). 解压 apache-tomcat-6.0.16.zip 到一个非中文目录下2). 配置一个环境变量. java_home(指向 JDK 安装的根目录) ...

  7. 集合框架学习笔记<三>

    一些重要的区别 set与list的区别: set是无索引的,list是有索引的: ArrayList与LinkList的区别: 前者是基于数组实现的,后者是基于链表实现的: 两者的使用方法一样,但是在 ...

  8. 在springmvc中使用hibernate-validate

    在springmvc.xml中加入 <!-- 国际化配置 --> <bean id="localeResolver" class="org.spring ...

  9. NGUI 3.x 练习

    一.常用快捷键 Alt+Shitf+W 创建一个新的 Widget Alt+Shift+S 创建一个新的 Sprite Alt+Shift+L 创建一个新的 Label Alt+Shift+T 创建一 ...

  10. Cursor的各种效果

    总结之后的Cursor的各种效果: http://sandbox.runjs.cn/show/bbwoyn0c http://css-cursor.techstream.org/ 源代码如下: < ...