昨天我正在研究一个方法并遇到了一些奇怪的事情,这里是代码的简化版本:基本上问题是在 Bar.PopulateList 方法中应用的 OrderBy 没有持久化。
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 theList) 和 Bar.PopulateList(ref MyObjects);
任何人都可以启发我吗?我认为对象总是由 ref 传递?OrderBy 是一种扩展方法吗?
谢谢, 西安