C# 3.0新功能

iDotNetSpace發表於2010-04-22
隱式型別的本地變數和陣列

var i = 5;

var a = new[] { 0, 1, 2 };

• 物件初始值設定項

private class Cat
{
     public int Age { get; set; }
     public string Name { get; set; }
}
static void MethodA()
{
      Cat cat = new Cat { Age = 10, Name = "Sylvester" }; {g , y };
}

• 集合初始值設定項

List digits = new List { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List digits2 = new List { 0 + 1, 12 % 3, MakeInt() };

• 自動實現的屬性

class LightweightCustomer
{
public double TotalPurchases { get; set; }
public string Name { get; private set; } // read-only
public int CustomerID { get; private set; } // read-only
}

• 匿名型別

var v = new { Amount = 108, Message = "Hello" };

• 擴充套件方法

namespace ExtensionMethods
{
public static class MyExtensions
{
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}  
}

using ExtensionMethods;
string s = "Hello Extension Methods";
int i = s.WordCount();

 

• 分部方法定義

// Definition in file1.cs
partial void onNameChanged();
// Implementation in file2.cs
partial void onNameChanged()
{
// method body // et od body
}

• Lambda 表示式

Lambda 表示式

var results = people.Where(p => p.LastName == "White");

delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

Lambda 語句

delegate void TestDelegate(string s);
… …
TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
myDel("Hello");

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-660395/,如需轉載,請註明出處,否則將追究法律責任。

相關文章