zoukankan      html  css  js  c++  java
  • Professional C# 6 and .NET Core 1.0

    本文为转载,学习研究

     

    What’s New in C# 6 

    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. 

    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?

     

    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 statement can 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.

  • 相关阅读:
    《梦幻西游》打响反盗号战役:为2亿玩家提供360安全武器 狼人:
    瑞星发表官方声明:记者王学武系恶意诽谤 狼人:
    中美联合挫败Conficker蠕虫大攻击 狼人:
    安全机构建议奥巴马政府谨慎使用开源软件 狼人:
    大量计算机遭“灰鸽子”病毒攻击 狼人:
    警惕IE7新漏洞导致的木马病毒暴增 狼人:
    IE7漏洞被瞄准 新型攻击将爆发 狼人:
    Windows 7成为Pwn2own黑客挑战赛目标 狼人:
    黑客入侵唱片业协会网站 为“海盗湾”助威 狼人:
    “猫癣”“犇牛”木马病毒肆虐 专家提醒补漏洞 狼人:
  • 原文地址:https://www.cnblogs.com/EasyInvoice/p/6367728.html
Copyright © 2011-2022 走看看