首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

《C# 3.0 in a Nutshell》之 C# 3.0 與 .NET 3.5 基礎介紹 (3) - 物件初始化設定、自動屬性、部分方法、運算式樹

     編輯:關於C語言

f. 物件初始化設定

省去大量建構函式,方便實例化:

Bunny b1 = new Bunny { Name = "Bo", LikesCarrots = true, LikesHumans = false };

g. 隱含型別陣列


var dudes = new[] 
{
    new { Name = "Bob", Age = 20 },
    new { Name = "Rob", Age = 30 }
};

h. 自動屬性

語法糖,簡化屬性宣告:


public class Stock
{
    // C# 3.0
    public decimal X { get; set; }
    
    // C# 2.0 寫法
    private decimal y;
    public decimal Y { get => y; set => y = value; }
}

i. 部分方法

宣告與實作分離,未實作時呼叫不報錯:


partial class PaymentForm 
{
    partial void ValidatePayment(decimal amount); // 宣告
}
partial class PaymentForm 
{
    partial void ValidatePayment(decimal amount)  // 實作
    { if (amount > 100) { /* ... */ } }
}
static void Main() 
{
    var form = new PaymentForm();
    form.ValidatePayment(5.3m); // 無實作也不會錯誤
}

j. 運算式樹


string[] names = { "Tom", "Dick", "Harry" };
IEnumerable<string> filteredNames = Enumerable.Where(names, n => n.Length >= 4);

以上皆為 C# 3.0 新特性,業界稱為「語法糖」。後續文章將詳細探討。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved