【Professional C# 6 and .NET Core 1.0】C#6的新特性

在C#6中有一个新的C#编译器。

1 静态的using 声明

静态的using声明允许调用静态方法时不使用类名。

//In C# 5 
using System;
Console.WriteLine("Hello,World!");

//In C# 6 
using static System.Console;
WriteLine("Hello,World"); 

2 表达式体方法

表达式体方法只包括一个可以用lambda语法编写的语句

//In C# 5 
public boolIsSquare(Rectangle rect)
{
  return rect.Height == rect.Width;
}

//In C# 6 
public boolIsSquare(Rectangle rect) => rect.Height == rect.Width;

3 表达式体属性

与表达式体方法类似,只有get存取器的单行属性可以用lambda语法编写

//In C# 5 
public string FullName
{
  get
  {
    return FirstName +"" + LastName;
  }
}

//In C# 6 
public string FullName=> FirstName +"" + LastName;

4 自动实现的属性初始化器

自动实现的属性可以用属性初始化器来初始化

//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;
}

5 只读的自动属性

为了实现只读属性,C#5需要使用完整的属性语法;而在C#6中,可以使用自动实现的属性

//In C# 5 
private readonly int_bookId;

public BookId
{
  get
  {
    return _bookId;
  }
}

//In C# 6
public BookId {get;}

6 nameof运算符

使用新的nameof运算符,可以访问字段名、属性名、方法名或类型名。这样,在重构时,就不会遗漏名称的改变

//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));

7 空值传播运算符

空值传播运算符简化了空值的检查

//In C# 5 
int? age = p == null ?null : p.Age;

//In C# 6 
int? age = p?.Age;

新语法也有触发事件的优点:

//In C# 5 
var handler = Event;
if (handler != null)
{
  handler(source, e);
}

//In C# 6 
handler?.Invoke(source,e);

8 字符串插值

字符串插值删除了对string.Format的调用,它不在字符串中使用编号的格式占位符,占位符可以包含表达式:

//In C# 5 
public override ToString()
{
  return string.Format("{0}, {1}",Title, Publisher);
}

//In C# 6
public override ToString()=> $"{Title} {Publisher}";

与C#5语法相比,C#6示例的代码减少了许多,不仅因为它使用了字符串插值,还使用了表达式体方法。字符串插值还可以使用字符串格式,把它分配给FormattableString时会获得特殊的功能。

9 字典初始化器

字典现在可以用字典初始化器来初始化,类似于集合初始化器。

//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"
};

10 异常过滤器

异常过滤器允许在捕获异常之前过滤它们。

//In C# 5 
try
{
  ...
}
catch (MyException ex)
{
  if (ex.ErrorCode != 405) throw;
  ...
}

//In C# 6 
try
{
  ...
}
catch (MyException ex)when (ex.ErrorCode == 405)
{
  ...
}

11 Catch中的await

await现在可以在catch子句中使用。C#5需要一种变通方法:

//In C# 5 
bool hasError = false;
string errorMessage =null;

try
{
  ...
}
catch (MyException ex)
{
  hasError = true;
  errorMessage = ex.Message;
}

if (hasError)
{
  await newMessageDialog().ShowAsync(errorMessage);
}

//In C# 6 
try
{
  ...
}
catch (MyException ex)
{
  await newMessageDialog().ShowAsync(ex.Message);
}
posted @ 2020-01-12 17:34  FH1004322  阅读(66)  评论(0)    收藏  举报