我昨天正在研究一個方法,並遇到了一些奇怪的問題,這裏是代碼的笨拙版本:基本上問題是OrderBy應用於Bar.PopulateList方法不是持久的。將對象傳遞給方法,然後調用該對象的擴展方法
class Foo
{
List MyObjects;
public void PopulateMyObjects()
{
//Items are added to my list but the OrderBy is not persisting.
Bar.PopulateList(MyObjects);
}
}
class Bar
{
public static int PopulateList(List theList)
{
foreach(var in WebSerbiceCall)
{
theList.Add(var);
}
// the OrderBy call only sorts 'theList' in the context of this method.
// When I return from this method theList has been populated but the Ordering has
// reverted back to the order that the items were added to the list.
theList.OrderBy(obj => obj.ID);
return theList.Count;
}
}
現在,如果我更新代碼,並添加ref關鍵字按下面的所有作品: 例如public static int PopulateList(ref List List) and Bar.PopulateList(ref MyObjects);
任何人都可以啓發我嗎?我以爲對象總是被ref引用? OrderBy是一種擴展方法嗎?
感謝,慈安
有序枚舉是否與未排序列表具有相同數量的元素? – dtb 2010-12-02 00:29:28
OrderBy上面有代碼:theList.Add(var);所以我不認爲這是可以假設的。 – jwwishart 2010-12-02 00:33:30
但OrderBy不添加或刪除任何元素,所以`theList.OrderBy(obj => obj.ID).Count()`應該等於`theList.Count`,否? – dtb 2010-12-02 01:05:19