MSXML和ADO.NET使我們能夠遍曆和操作XML文檔,但它們都無法讓開發人員在編寫資料訪問作業碼時覺得舒服、自然。
LINQ使資料訪問成為了.NET中的一個進階編程概念,它使得開發人員能夠完全依靠智能感知技術來建立型別安全的資料存取碼和編譯期的語法檢查。
using語句是try...finally的簡潔表示。當所建立的類型實現了IDisposable時,則可以直接使用using。
匿名方法(anonymous method)
// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
{ System.Windows.Forms.MessageBox.Show("Click!"); };
對象、集合初始化器文法,編譯器會將集合初始化代碼轉換成完整的形式,節省出大量的編碼時間。P28 《LINQ編程技術內幕》
Chapter 3: 擴充方法(Extension Method): 允許擴充密封類和內部類型,它還能避免深度繼承樹,它提供了一種無需繼承的添加行為的方式。
樣本示範了如何添加一個名為Dump的擴充方法,第一個參數類型之前必需使用this修飾符。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var song = new { Artist = "JUssi", Song = "Aida" };
song.Dump();
Console.Read();
}
}
public static class Dumper
{
public static void Dump(this Object o) // 作用於object類型,而所有類型又都繼承自object.
{
PropertyInfo[] properties = o.GetType().GetProperties();
foreach (PropertyInfo p in properties)
{
try
{
Debug.WriteLine(string.Format("Name: {0}, Value: {1}", p.Name,
p.GetValue(o, null)));
}
catch
{
Debug.WriteLine(string.Format("Name: {0}, Value: {1}", p.Name,
"unk."));
}
}
}
public static void Dump(this IList list)
{
foreach(object o in list)
o.Dump();
}
}
}
P60~64樣本3-6和3-8對比,說明Linq使得代碼更加簡潔。Linq的基礎就是擴充方法(還有泛型),where就是一個用於擴充IQueryable的擴充方法。
Chapter 4: yield return關鍵字片語能夠將本身不是可迭代集合的對象做成可迭代集合。它不能出現在catch塊中,也不能出現在帶有一個或多個catch子句的try塊中。yield語句不能出現在匿名方法中。
Chapter 5:
1.
delegate void FunctionPointer(string str);
FunctionPointer fp = s=>Console.WriteLine(s);
fp("hello world");
2.
System.Action<string> fp = s=>Console.WriteLine(s);
fp("hello world");
Func用於在參數上執行一個操作並返回一個值;
Predicate用於定義一組條件並確定參數是否符合這些條件。