我如何让SingleOrDefault从列表中引用返回对象

本文关键字:引用 返回 对象 列表 SingleOrDefault | 更新日期: 2023-09-27 18:04:20

考虑以下几行代码:

  //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保持不变,证明它们没有引用列表中的内容。为什么会这样?是否有一种方法可以更新列表中对象的值?

我如何让SingleOrDefault从列表中引用返回对象

如果您的ProductionCostCalcHelper类型是可变的struct,则会发生这种情况。
不要那样做;可变结构体是邪恶的

每次你传递一个struct,整个值被复制到你传递给它的任何地方。