本文为转载,学习研究

What’s New in C# 6

With C# 6 a new C# compiler is available. It’s not only that a source codecleanup

was done; the features of the compiler pipeline can now be used from custom

programs, and are used by many features of Visual Studio.

This new compiler platform made it possible to enhance C# with many new

features. Although there’s not a feature with such an impact as LINQ orthe async

keyword, the many enhancements increase developer productivity. What arethe

changes of C# 6?

static using

The static using declarationallows invoking static methods without the class

name:

In C# 5

using System;

// etc.

Console.WriteLine("Hello,World!");

In C# 6

using static System.Console;

// etc.

WriteLine("Hello,World");

The using static keyword iscovered in Chapter 2, “Core C#.”

Expression-Bodied Methods

With expression-bodied methods, a method that includes just one statementcan

be written with the lambda syntax:

In C# 5

public boolIsSquare(Rectangle rect)

{

return rect.Height == rect.Width;

}

In C# 6

public boolIsSquare(Rectangle rect) => rect.Height == rect.Width;

Expression-bodied methods are covered in Chapter 3, “Objects and Types.”

Expression-Bodied Properties

Similar to expression-bodied methods, one-line properties with only a getaccessor

can be written with the lambda syntax:

In C# 5

public string FullName

{

get

{

return FirstName +"" + LastName;

}

}

In C# 6

public string FullName=> FirstName +"" + LastName;

Expression-bodied properties are covered in Chapter 3.

Auto-Implemented PropertyIntializers

Auto-implemented properties can be initialized with a propertyinitializer:

In C# 5

public class Person

{

public Person()

{

Age = 24;

}

public int Age {get; set;}

}

In C# 6

public class Person

{

  public int Age {get; set;} = 42;

}

Auto-implemented property initializers are covered in Chapter 3.

Read-Only Auto Properties

To implement read-only properties, C# 5 requires the full property syntax.With

C# 6, you can do this using auto-implemented properties:

In C# 5

private readonly int_bookId;

public BookId

{

get

{

return _bookId;

}

}

In C# 6

public BookId {get;}

Read-only auto properties are covered in Chapter 3.

nameof Operator

With the new nameof operator, namesof fields, properties, methods, or types can

be accessed. With this, name changes are not missed with refactoring:

In C# 5

public void Method(objecto)

{

if (o == null) throw newArgumentNullException("o");

In C# 6

public void Method(objecto)

{

if (o == null) throw newArgumentNullException(nameof(o));

The nameof operator iscovered in Chapter 8, “Operators and Casts.”

Null Propagation Operator

The null propagation operator simplifies null checks:

In C# 5

int? age = p == null ?null : p.Age;

In C# 6

int? age = p?.Age;

The new syntax also has an advantage for firing events:

In C# 5

var handler = Event;

if (handler != null)

{

handler(source, e);

}

In C# 6

handler?.Invoke(source,e);

The null propagation operator is covered in Chapter 8.

String Interpolation

The string interpolation removes calls to string.Format. Instead of using

numbered format placeholders in the string, the placeholders can include

expressions:

In C# 5

public override ToString()

{

return string.Format("{0}, {1}",Title, Publisher);

}

In C# 6

public override ToString()=> $"{Title} {Publisher}";

The C# 6 sample is reduced that much compared to the C# 5 syntax becauseit

uses not only string interpolation but also an expression-bodied method.

String interpolation can also use string formats and get special featureson

assigning it to a FormattableString. Stringinterpolation is covered in Chapter 10,

“Strings and Regular Expressions.”

Dictionary Initializers

Dictionaries can now be initialized with a dictionary initializer—similarto the

collection initializer.

In C# 5

var dict = newDictionary<int, string>();

dict.Add(3,"three");

dict.Add(7,"seven");

In C# 6

var dict = newDictionary<int, string>()

{

[3] ="three",

[7] ="seven"

};

Dictionary initializers are covered in Chapter 11, “Collections.”

Exception Filters

Exception filters allow you to filter exceptions before catching them.

In C# 5

try

{

//etc.

}

catch (MyException ex)

{

if (ex.ErrorCode != 405) throw;

// etc.

}

In C# 6

try

{

//etc.

}

catch (MyException ex)when (ex.ErrorCode == 405)

{

// etc.

}

A big advantage of the new syntax is not only that it reduces the codelength but

also that the stack trace is not changed—which happens with the C# 5variant.

Exception filters are covered in Chapter 14, “Errors and Exceptions.”

Await in Catch

await can now be usedin the catch clause. C# 5required a workaround.

In C# 5

bool hasError = false;

string errorMessage =null;

try

{

//etc.

}

catch (MyException ex)

{

hasError = true;

errorMessage = ex.Message;

}

if (hasError)

{

await newMessageDialog().ShowAsync(errorMessage);

}

In C# 6

try

{

//etc.

}

catch (MyException ex)

{

await newMessageDialog().ShowAsync(ex.Message);

}

This feature doesn’t need an enhancement of the C# syntax; it’sfunctionality

that’s working now. This enhancement required a lot of investment from

Microsoft to make it work, but that really doesn’t matter to you usingthis

platform. For you, it means less code is needed—just compare the twoversions.

NOTE The new C# 6 language features are covered in the mentioned

chapters, and in all chapters of this book the new C# syntax isused.

Professional C# 6 and .NET Core 1.0 - What’s New in C# 6的更多相关文章

  1. Professional C# 6 and .NET Core 1.0 - 37 ADO.NET

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 37 ADO.NET -------- ...

  2. Professional C# 6 and .NET Core 1.0 - 38 Entity Framework Core

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 38 Entity Framework ...

  3. Professional C# 6 and .NET Core 1.0 - Chapter 39 Windows Services

    本文内容为转载,供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - Chapter 39 Windows Servi ...

  4. Professional C# 6 and .NET Core 1.0 - 40 ASP.NET Core

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 40 ASP.NET Core --- ...

  5. Professional C# 6 and .NET Core 1.0 - Chapter 43 WebHooks and SignalR

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - Chapter 43 WebHooks ...

  6. Professional C# 6 and .NET Core 1.0 - Chapter 38 Entity Framework Core

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - Chapter 38 Entity F ...

  7. Professional C# 6 and .NET Core 1.0 - Chapter 37 ADO.NET

    本文内容为转载,供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处:Professional C# 6 and .NET Core 1.0 - 37 ADO.NET 译文:C# 6 与 .NE ...

  8. Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

    What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Valida ...

  9. Professional C# 6 and .NET Core 1.0 - Chapter 42 ASP.NET Web API

    本文内容为转载,重新排版以供学习研究.如有侵权,请联系作者删除. 转载请注明本文出处: -------------------------------------------------------- ...

  10. Professional C# 6 and .NET Core 1.0 - Creating Hello, World! with Visual Studio

    本文为转载,学习研究 Creating Hello, World! with Visual Studio Chapter 1, “.NET Application Architectures,” ex ...

随机推荐

  1. MongoDB 3.0 WiredTiger Compression and Performance

    MongoDB3.0中的压缩选项 在MongoDB 3.0中,WiredTiger为集合提供三个压缩选项: 无压缩 Snappy(默认启用) – 很不错的压缩,有效利用资源 zlib(类似gzip) ...

  2. 关于安装Windows Live Writer后,内存被占满情况解决

    为了方便写博客,昨天安装了Windows Live Writer2012,但是出现了在安装好后还是正常的,第二天一开机就出现了内存被占满的情况,在资源监视器里看了下也没发现有什么问题.想还是重启一下, ...

  3. 重启机器解决SSL都要输入密码问题

    在Nginx或Apache设置了SSL加密后,发现每次重启服务器后都要输入证书设置的密码,比较麻烦,不然Nginx或Apache无法使用,这时可以用私钥来做这件事.生成一个解密的key文件,替代原来k ...

  4. 火狐上的一个post提交工具(主要用于测试接口时候)

    添加的过程 安装完后,就可以在下图上,看到一个poster 点击poster就可以看到下图 图中红线圈好的,是必须要填写的 Url是访问路径 Name是参数名称 Value是参数值 需要注意一点的是: ...

  5. abs函数

    absolute 绝对值函数 abs函数是一个取绝对值函数,你得确保ABS()括号里的表达式所计算出的结果是数字,String是字符串的意思,你括号你的数据肯定是字符串了,如果A.B两变量你是这样定义 ...

  6. 【转】我是怎么找到电子书的 – IT篇

    多读书,提高自己 电子出版物 IT-ebooks http://it-ebooks.info/ 上万本英文原版电子书,大多数为apress和o'relly的.全都是文字版,体积小又清楚.适合懂英文的人 ...

  7. git 常用命令--Linus Torvalds

    1.git log 显示仓库的历史记录,默认显示所有记录, 1)git log -m,显示最近的几次提交,, 2)git log --pretty=oneline  显示提交hash和注释 -p 按补 ...

  8. Leetcode 182. Duplicate Emails

    Write a SQL query to find all duplicate emails in a table named Person. +----+---------+ | Id | Emai ...

  9. MongoDB升级教程

    1.排序 sort()方法:其中 1 为升序排列,而-1是用于降序排列. db.col.find({},{"title":1,_id:0}).sort({"likes&q ...

  10. javah编译class文件找不到android.app.Activity的类文件

    在android工程的根目录使用javah生成jni 头文件时候,报找不到android.app.Activity的类文件错误. 无法访问android.app.Activity是说明没有引入andr ...