【澳门葡京备用网址】十个新特点

1. 静态using(static using)

静态using注解允许不选用类名直接调用静态方法。

The static using declaration allows invoking static methods without
the class
name.

In C# 5

using System;

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

In C#【澳门葡京备用网址】十个新特点。 6

using static System.Console;

WriteLine("Hello, World");

本文为转发,学习研商

Static Using

static using证明允许直接调用静态方法而无需钦点类名:

2. 表明式方法(Expression-Bodied Methods)

应用表明式方法,唯有一条语句的办法能够采纳lambda语法写。

With expression-bodied methods, a method that includes just one
statement can
be written with the lambda syntax.

In C# 5

public bool IsSquare(Rectangle rect)
{
    return rect.Height == rect.Width;
}

In C# 6

public bool IsSquare(Rectangle rect) => rect.Height == rect.Width;

 

C# 5

static void StaticUsingDemoInCSharp5(string output)
{
    Console.WriteLine(output); // Call the static method WriteLine with class name Console
}

C# 6

using static System.Console;

namespace NewFeatureTest
{
    class Program
    {
        static void Main(string[] args)
        {
            StaticUsingDemoInCSharp6("Hello, C# 6");
        }

        static void StaticUsingDemoInCSharp6(string output)
        {
            WriteLine(output);
        }
    }
}

三. 表明式属性(Expression-Bodied Properties)

跟表明式方法类似,唯有贰个get访问器的单行属性能够使用lambda语法写。

Similar to expression-bodied methods, one-line properties with only a
get accessor
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;

What’s New in C# 6 

Expression-Bodied Methods

使用expression-bodied
methods,三个唯有一句statement的函数能够运用lambda写法。

C# 5

private static bool IsIntegerEqual(int a, int b)
{
    return a == b;
}

C# 6

private static bool IsIntegerEqualWithExpressionBodied(int a, int b) => a == b;

四. 活动属性开头化器(Auto-Implemented Property Intializers)

自动属性能够使用品质开始化器发轫化。

Auto-implemented properties can be initialized with a property
initializer.

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

With C# 6 a new C# compiler is available. It’s not only that a source
code cleanup was done; the features of the compiler pipeline can now be
used from custom programs, and are used by many features of Visual
Studio. 

Expression-Bodied Properties

和expression-bodied
methods类似,只支持get访问器且唯有一句statement的习性(Properties)也得以运用lambda写法。

五. 只读自动属性(Read-Only Auto Properties)

C# 5供给总体的属性语法达成只读属性,C# 陆能够选用机关属性实现。

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

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 are the changes of C# 6?

C# 5

private string firstName;

public string FirstName
{
    get
    {
        return firstName;
    }
}

6. nameof操作符(nameof Operator)

字段、属性、方法和花色的name能够由此nameof访问。使用nameof,能够便宜的重构name变化。

With the new nameof operator, names of fields, properties, methods, or
types can
be accessed. With this, name changes are not missed with refactoring.

In C# 5

public void Method(object o)
{
    if (o == null) throw new ArgumentNullException("o");

In C# 6

public void Method(object o)
{
    if (o == null) throw new ArgumentNullException(nameof(o));

 

C# 6

private string lastName;

public string LastName => lastName;

7. Null传递操作符(Null Propagation Operator)

Null传递操作符简化了空值检查。

The null propagation operator simplifies null checks.

In C# 5

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

var handler = Event;
if (handler != null)
{
    handler(source, e);
}

In C# 6

int? age = p?.Age;

handler?.Invoke(source, e);

static using 

Auto-Implemented Property Initializers

Auto-implemented  Property能够在二本性能早先化器里开首化。

捌. 字符串插值(String Interpolation)

字符串差值移除了对string.Format的调用,使用表明式占位符代替数字格式占位符。

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 static using declarationallows invoking static methods without the
class name:

C# 5

public string Sex { get; set; }

public Person()
{
    Sex = "Male";
}

玖. 字典初步化器(Dictionary Initializers)

字典能够应用类似集结的字典伊始化器初叶化。

Dictionaries can now be initialized with a dictionary
initializer—similar to the
collection initializer.

In C# 5

var dict = new Dictionary<int, string>();
dict.Add(3,"three");
dict.Add(7,"seven");

In C# 6

var dict = new Dictionary<int, string>()
{
    [3] ="three",
    [7] ="seven"
};

 In C# 5 

C# 6

public int Age { get; set; } = 42; // The age will be initialized to 42 when object constructed

十. 尤其过滤器(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.
}

using System;

Read-Only Auto Properties

在前头的C#本子中,只读属性须求完整的属性语法。C#陆提供了机动实现的本子:

11. 在Catch使用Await(Await in Catch)

await能够在catch块中一直动用,C# 5中须要扭转使用。

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

In C# 5

bool hasError = false;
string errorMessage = null;
try
{
    //etc.
} catch (MyException ex)
{
    hasError = true;
    errorMessage = ex.Message;
} 
if (hasError)
{
    await new MessageDialog().ShowAsync(errorMessage);
}

In C# 6

try
{
    //etc.
} catch (MyException ex)
{
    await new MessageDialog().ShowAsync(ex.Message);
}

// etc.

C# 5

private readonly string homeTown;

public string HomeTown { get { return homeTown; } }

Console.WriteLine(“Hello,World!”);

C# 6

public string BirthDay { get; }
public Person(string _firstName, string _lastName)
{
        BirthDay = DateTime.Today.ToString();
}

 

nameof Operator

行使最新的nameof操作符,字段(田野先生s)、属性(Properties)、方法和项目标名字都能被取到。有了它,老母在也不用顾忌改名字的时候会挂一漏万啦。

In C# 6 

C# 5

public bool IsAdult(int age)
        {
            if (age < 0)
            {
                throw new ArgumentException("age");
            }

            return age >= 18;
        }

using static System.Console;

C# 6

public bool IsAdultWithNameOfOperator(int age)
        {
            if (age < 0)
            {
                throw new ArgumentException(nameof(age));
            }

            return age >= 18;
        }

// etc.

Null Propagation Operator

null propagation操作符可以大大滴简化空对象的自己争论。

WriteLine(“Hello,World”); 

C# 5

public Person(int? _age)
{
    Age = _age == null ? -1 : _age.Value;
}

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

C# 6

public Person(DateTime? _birthDay)
{
    birthDay = _birthDay?.ToString();
}

 

String Interpolation

在c#陆中,字符串插值无需再call
string.Format方法啦。相较于事先在string中使用数字占位符如{0},C#陆扶助表达式占位符如{age}。

Expression-Bodied Methods 

C# 5

public override string ToString()
{
    return string.Format("{0} {1}”, firstName, lastName);
}

With expression-bodied methods, a method that includes just one
statement can be written with the lambda syntax: 

C# 6

public override string ToString() => $"{firstName} {lastName}";

在此地,大家运用了新的string interpolation和expression-bodied
method让漫天代码相较于事先简洁诸多(按代码行数算钱的码农悲催了)。

In C# 5 

Dictionary Initializers

在C#
6中,大家得以像集结开端化器一样使用字典(Dictionary)开头化器来初步化字典对象。

public boolIsSquare(Rectangle rect)

C# 5

var dictInCSharp5 = new Dictionary<int, string>()
{
    {2, "Two"},
    {1, "One"}
};

{

C# 6

var dictInCSharp6 = new Dictionary<int, string>()
{
    [2] = "Two",
    [1] = "One"
};

那东西个人感到没什么用,反而轻易和Collection的下标混淆。

  return rect.Height == rect.Width;

Exceptions Filters

非常过滤器允许大家在catch万分从前运用标准来过滤格外。

}

C# 5

try
{
    StaticUsingDemoInCSharp6(p.LastName);
}
catch (Exception e)
{
    if (e.Message.Contains("Aha"))
    {
        throw;
    }
}

 

C# 6

try
{
    StaticUsingDemoInCSharp6(p.LastName);
}
catch(Exception e) when (e.Message.Contains("Aha"))
{
    throw;
}

In C# 6 

Await in Catch

C#六允许我们在catch程序块里面使用await关键字。在c#5我们不得不workaround。

C# 5

private static async Task AwaitInCatchDemoInCSharp5()
{
    bool hasError = false;
    string errorMessage = string.Empty;

    try
    {
        throw new FieldAccessException("No Permission.");
    }
    catch(FieldAccessException e)
    {
        hasError = true;
        errorMessage = e.Message;
    }

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

C# 6

private static async Task AwaitInCatchDemoInCSharp5()
{

    try
    {
        throw new FieldAccessException("No Permission.");
    }
    catch(FieldAccessException e)
    {
        await MessageDialog().ShowAsync(e.Message);
    }

}

参考: 《Professional C#6 and .NET Core 1.0》

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.

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*
*
Website