如何使SingleOrDefault通过列表中的引用返回对象?

时间:2011-08-03 19:16:29

标签: c# .net linq byref

考虑以下几行代码:

  //prodProdGroup is a list within the itm object that I need to search. The items
  //within the list are of type ProductionCostCalcHelper. I need to find one
  //of the ProductionCostCalcHelper records in the list, calculate its total dollar value
  //and assign it the value

  ProductionCostCalcHelper prodGroupItm = itm.prodProdGroup.SingleOrDefault(f => f.MAST_PROJ.Trim() == laborItm.MAST_PROJ.Trim());
  ProductionCostCalcHelper prodGroupItm2 = itm.prodProdGroup.SingleOrDefault(f => f.MAST_PROJ.Trim() == laborItm.MAST_PROJ.Trim());

  if (prodGroupItm != null)
  {
        prodGroupItm.TOTAL_DOLLAR = avgDollarsPerHour * prodGroupItm.HOURS;
  }

我假设SingleOrDefault方法会通过引用返回对象,但事实并非如此。更改ProdGroupItm的TOTAL_DOLLAR数量后,ProdGroupItm2保持不变,证明它们没有引用列表中的内容。为什么是这样?有没有办法更新列表中对象的值?

1 个答案:

答案 0 :(得分:1)

如果您的ProductionCostCalcHelper类型是可变struct,则会发生这种情况 不要那样做; mutable structs are evil

每次传递struct时,整个值都会复制到您传递给它的任何地方。

改为使用班级。