2009-10-29 134 views
3

如果我使用lambda表達式像下面C#Lambda表達式幫助

// assume sch_id is a property of the entity Schedules 
public void GetRecord(int id) 
{ 
    _myentity.Schedules.Where(x => x.sch_id == id)); 
} 

我假設(儘管未測試),我可以重寫,使用使用的東西一個匿名內聯函數像

_jve.Schedules.Where(delegate(Models.Schedules x) { return x.sch_id == id; }); 

我的問題是,我將如何重寫,在一個正常的(非內聯)功能,仍然通過ID參數。

回答

7

簡短的回答是,你不能讓它成爲一個stand-along功能。在你的例子中,id實際上保存在closure中。

長的答案是,您可以編寫一個類來捕獲狀態,方法是用要操作的id值進行初始化,並將其存儲爲成員變量。在內部,閉包的操作方式相似 - 區別在於它們實際上捕獲對變量的引用,而不是其副本。這意味着閉包可以「看到」它們所綁定變量的變化。有關詳細信息,請參閱上面的鏈接。

因此,舉例來說:

public class IdSearcher 
{ 
    private int m_Id; // captures the state... 
    public IdSearcher(int id) { m_Id = id; } 
    public bool TestForId(in otherID) { return m_Id == otherID; } 
} 

// other code somewhere... 
public void GetRecord(int id) 
{ 
    var srchr = new IdSearcher(id); 
    _myentity.Schedules.Where(srchr.TestForId); 
} 
+1

ID不是封閉自己;它只是在關閉中存儲的狀態。 – 2009-10-29 17:52:28

0

您將需要保存在某個地方的ID。這是由using a closure爲您完成,基本上就像創建一個單獨的,具有值和方法的臨時類。

1

如果你只想把委託其他地方的身體,你可以實現使用此

public void GetRecord(int id) 
{ 
    _myentity.Schedules.Where(x => MyMethodTooLongToPutInline(x, id)); 
} 
private bool MyMethodTooLongToPutInline(Models.Schedules x, int id) 
{ 
    //... 
}