出於對Lambda的好奇所以學習了一下,看能不能通過Lambda來開啟新的更用效的代碼編寫方式。以下是通過Lambda實現一個通用型的遞迴控制處理函數。這隻是一個參考,實際上你可以挖掘Lambda更多的使用方法.多謝 裝配腦袋 指出問題重新調整一下代碼(這裡本意不是描述該方法功能如何,而是想體現Lambda的引發的雖一種編碼方式). using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace lambdaTest
{
public delegate void EventExecute<T>(T source, Program.Recursive<T> next);
public static class Program
{
static void Main(string[] args)
{
UnderList ul = new UnderList();
ul.EmployeeID = 2;
string sql = "select EmployeeID,FirstName from Employees where ReportsTo={0}";
using (System.Data.SqlClient.SqlConnection conn
= new System.Data.SqlClient.SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True"))
{
conn.Open();
Do<UnderList>(ul, p => (p.EmployeeID > 0),
delegate(UnderList source, Program.Recursive<UnderList> r)
{
source.Format += "\t";
List<int> mUnders = new List<int>();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = string.Format(sql, source.EmployeeID);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
mUnders.Add((int)reader[0]);
Console.WriteLine(source.Format + reader[1]);
}
private static void Do<T>(T i, Func<T, bool> a, EventExecute<T> e)
{
Program.Recursive<T> rec = new Recursive<T>(i,e,a);
e(i, rec);
}
public class Recursive<T>
{
public Recursive(T source, EventExecute<T> e, Func<T, bool> expression)
{
Source = source;
E = e;
Expression = expression;
}
private T Source;
private EventExecute<T> E;
Func<T, bool> Expression;
public void Do()
{
if (Expression(Source))
E(Source, this);
}
}
}
public class UnderList
{
private int mEmployeeID;
public int EmployeeID
{
get
{
return mEmployeeID;
}
set
{
mEmployeeID = value;
}
}
public string Format = "";