不能在匿名方法中使用 ref 或 out 参数

Cannot use ref or out parameter inside an anonymous method

如果有人可以帮助解决我的问题,我的 C# 代码有问题。

在一个函数中,我正在解析一个 Xml 文件并将其保存到一个结构中。

然后我尝试从具有特定节点 ID 的所述结构中检索一些信息,但我的代码失败并显示

"Cannot use ref or out parameter 'c' inside an anonymous method, lambda expression, or query expression"

这是我的代码:

public void XmlParser(ref Point a, ref Point b, ref Point c)
{
     XDocument xdoc = XDocument.Load(XmlDirPath); 
     var coordinates = from r in xdoc.Descendants("move")
                        where int.Parse(r.Attribute("id").Value) == c.NodeID  // !! here is the error !!
                        select new
                        {
                              X = r.Element("x").Value,
                              Y = r.Element("y").Value,
                              Z = r.Element("z").Value, 
                              nID = r.Attribute("id").Value
                         };

     foreach (var r in coordinates)
     {
          c.x = float.Parse(r.X1, CultureInfo.InvariantCulture);
          c.y = float.Parse(r.Y1, CultureInfo.InvariantCulture);
          c.z = float.Parse(r.Z1, CultureInfo.InvariantCulture);
          c.NodeID = Convert.ToInt16(r.nID);
     }
}

public struct Point
{
    public  float x;
    public  float y;
    public  float z;
    public  int   NodeID;
}

您应该从匿名方法中提取 ID 的检索:

var nodeId = c.NodeID;

var coordinates = from r in xdoc.Descendants("move")
                           where int.Parse(r.Attribute("id").Value) == nodeId

嗯,您不能在匿名方法或 lambda 中使用 refout 参数,正如编译器错误所说。

相反,您必须将 ref 参数的值复制到局部变量中并使用它:

var nodeId = c.NodeID;
var coordinates = from r in xdoc.Descendants("move")
    where int.Parse(r.Attribute("id").Value) == nodeId
    ...

正如其他答案中所建议的那样,您必须在您的方法中本地复制 ref 变量。您必须这样做的原因是因为 lambdas/linq 查询更改了它们捕获的变量的生命周期,导致参数比当前方法框架的寿命更长,因为在方法框架不再位于堆叠.

有一个有趣的答案 here 仔细解释了为什么不能在匿名方法中使用 ref/out 参数。