C# 經過多年的改進,功能愈來愈強大,下一版的 C# 6.0 目前也已經包含在 Visual Studio 2014 CTP 裡,本篇文章將會介紹幾個比較重要的功能。

Auto Properties

定義類別時,如果要設定 Property 的預設值,只能在建構子裡設定,而在 C# 6.0 可以這樣定義:

    public class Foo
    {
        //auto property
        public int x { get; set; } = 1;
        public int y { get; set; } = 2;
    }

 

Primary Constructors

在定義建構子時,可以把最重要且必須要執行的建構子定義在最外層,而且還可以搭配 Auto Properties:

    public class Foo(int x, int y)
    {
		public Foo() :this(0,0)
		{
		}

        //auto properties
        public int x { get; set; } = x;
        public int y { get; set; } = y;
    }

 

Declaration Expressions

其實就是一個可以少打幾個字的變數宣告方式:

string strValue = "3";
int.TryParse(strValue, out int intValue);

變數 intValue 就直接在 TryPase 裡直接宣告。

 

Static Using Statements

這個設計真的造福了所有的 C# 程式設計師,想想每次要列印文字,都一定得打上 Console.WriteLine,但以後可以簡化成以下程式碼:

using System;
using System.Console;   //Static Using

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("A");
            WriteLine("B");
            WriteLine("C");
        }
    }
}

以往 Using 後面只能接 Namespace,但在 C# 6.0 裡,後面能直接放 static class。

 

Expression Bodied Functions and Properties

這功能算是一個語法蜜糖,當類別裡的方法較為單純時,可以用下列的方式宣告:

    public class Foo(int x, int y)
    {
        public int Add(int x, int y) => x + y;
        public string GetString() => "aaa3";
		public string MyString => "aaa3";
    }
arrow
arrow
    全站熱搜

    卑微研究生 發表在 痞客邦 留言(0) 人氣()