c# 6.0新特性(一)


寫在前面

接近年底了,基本上沒什么活了,就學點新東西,就想着了解下c# 6.0的新特性。在code project上看到了一篇不錯的文章,就准備翻譯一下,順便照着學習學習。廢話不多說,直奔主題。

原文地址:http://www.codeproject.com/Articles/1070659/All-About-Csharp-New-Features

簡介

眾所周知,c# 6.0 是在visual studio 2015中引入的。在其他的幾個版本中同樣引入一些特性,比如在c# 3.0中引入了linq,在c# 4.0中引入了動態類型dynamic,在c#5.0中引入async和await等等。

在c# 6.0更多關注了語法的改進,而不是增加新的功能。這些新的語法將有助於我們更好更方便的編寫代碼。

背景

你可以通過下載visual studio2015或者你已經安裝了visual studio2013,然后從這里(https://github.com/dotnet/roslyn)下載roslync包。Roslync是一個開源的並且和visual studio 2015繼承的.net 編譯器。

以下是c# 6.0的幾種改善的新的語法:

1、Using Static:使用static

2、Auto Property Initializers:自動屬性初始化

3、Index Initializers:索引初始化

4、String Interpolation:字符串插入

5、Expression Bodied Members

6、Getter Only Auto Properties:只讀自動屬性

7、Exception Filters:異常過濾器

8、Null Conditional Operators:null條件操作符

9、Declaration Expressions:聲明表達式

using static

這是一件在你的編程生涯中非常有用的一個特性。現在你可以通過using 關鍵字訪問類的屬性和方法了。實現這個,你只需要在你類的命名空間前using之后static關鍵字就可以了。

using static System.Console;

當我們使用using引用了System.Console這個類。那么我們就可以訪問這個類的所有屬性和方法。下面看一個在c# 6.0之前和之后我們是如何做的例子:

Before C# 6.0

using System;
namespace CplusplusNewFeature
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(" C# 6.0新特性");
        }
    }
}

在c# 6.0之前,如果我們要使用WrilteLine()方法,我們使用Console.WriteLine()。如果沒有引用Console這個類,我們是無法訪問這個方法的。

C# 6.0中

using System;
using static System.Console;
using static CplusplusNewFeature.MyClass;
namespace CplusplusNewFeature
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("c# 6.0 新特性");
            Hello();
            ReadLine();
        }
    }
    static class MyClass
    {
        public static void Hello()
        {
            WriteLine("This is static class");
        }
    }
}

C# 6.0在使用這個類的時候並不需要每次都引用這個類。我們只需要在using中聲明這個類,那么我們就可以訪問到它。

當然,我們也可以引用其他的類並訪問它的成員。

在上面的例子中,我們使用了MyClass類的Hello()方法。

 static class MyClass
    {
        public static void Hello()
        {
            WriteLine("This is static class");
        }
    }

在這里我們使用using引入了命名空間了,如下所示:

using static CplusplusNewFeature.MyClass;

Auto Property Initializers

我們使用屬性訪問內部成員。屬性有setter和getter方法。在c# 6.0之前,我們並不能直接為屬性賦值。如果真要這么做,我們只能通過屬性對應的字段來初始化。但是c# 6.0提供更靈活的方式。

通過c# 6.0我們可以在定義屬性的時候直接為它賦值。

Before C# 6.0

之前我們通過構造函數初始化屬性。看下面的例子,在這里我們創建了多個屬性,並在構造函數中為他們賦值。

using System;
using static System.Console;
namespace CplusplusNewFeature
{
    public class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            Console.WriteLine("Employee Id is " + emp.EmployeeId);
            Console.WriteLine("Employee Full Name is " + emp.FullName);
            Console.ReadLine();
        }
    }
    public class Employee
    {
        public Guid EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public string FullName { get; set; }
        public Employee()
        {
            EmployeeId = Guid.NewGuid();
            FirstName = "Mukesh";
            LastName = "Kumar";
            FullName = string.Format("{0} {1}", FirstName, LastName);
        }
    }
}

C# 6.0中

但是在c#6.0中非常方便,我們不必擔心怎么、在哪兒初始化屬性值。你可以直接在屬性后面通過=asign指定屬性的值。這種方式不會引發異常並且可以正常運行。在下面的例子中,我們可以看到EmplyeeId,FirstName,lastName初始化。

using System;
using static System.Console;
namespace CplusplusNewFeature
{
    public class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            WriteLine("Employee Id is " + emp.EmployeeId);
            WriteLine("Employee Full Name is " + emp.FullName);
            ReadLine();
        }
    }
    public class Employee
    {
        public Guid EmployeeId { get; set; } = Guid.NewGuid();
        public string FirstName { get; set; } = "Mukesh";
        public string LastName { get; set; } = "Kumar";

        public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }

    }
}

Index Initializers

c#6.0提供了一種新的初始化集合的方式。你可以創建想字典,hashtable一樣的集合。眾所周知,字典是鍵值對形式的,並且為對應的key指定value。在c#6.0之前,我們有很多不同的方式去創建鍵值對。看一下下面的在c#中c#6.0之前怎么使用鍵值對字典的。

using System;
using System.Collections.Generic;
namespace CplusplusNewFeature
{
    public class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> myDictionary = new Dictionary<int, string>() {
                {1, "Mukesh Kumar" },
                {2, "Rahul Rathor" },
                {3, "Yaduveer Saini" },
                {4, "Banke Chamber" }
            };

            foreach (var item in myDictionary)
            {
                Console.WriteLine("The " + item.Key + " Number Employee is " + item.Value + "\n");
            }
            Console.ReadLine();
        }
    }
}

In c#6.0

但是在c#6.0中,我們可以邏輯上為索引為1的指定“Mukes Kumar”的值,其它的以此類推。你可以看看下面的這個例子,將消除你所有的疑慮。

using System;
using System.Collections.Generic;
using static System.Console;
namespace CplusplusNewFeature
{
    public class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> myDictionary = new Dictionary<int, string>()
            {
                [1] = "Mukesh Kumar",
                [2] = "Rahul Rathor",
                [3] = "Yaduveer Saini",
                [4] = "Banke Chamber"
            };

            foreach (var item in myDictionary)
            {
                WriteLine("The " + item.Key + " Number Employee is " + item.Value + "\n");
            }
            ReadLine();
        }
    }
}

總結

之前也看過這方面的文章,沒動手實現過,今天嘗試了下,發現非常的方便。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM