C# 无法在匿名方法内使用ref或out参数

C# 无法在匿名方法内使用ref或out参数,c#,xml,lambda,C#,Xml,Lambda,我的c语言代码有问题,如果有人能帮我解决问题 在一个函数中,我解析一个Xml文件并将其保存到一个结构 然后我尝试用一个特定的节点id从这个结构中检索一些信息,我的代码失败了 无法在匿名方法、lambda表达式或查询表达式中使用ref或out参数“c” 这是我的密码: public void XmlParser(ref Point a, ref Point b, ref Point c) { XDocument xdoc = XDocument.Load(XmlDirPath);

我的c语言代码有问题,如果有人能帮我解决问题

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

然后我尝试用一个特定的节点id从这个结构中检索一些信息,我的代码失败了

无法在匿名方法、lambda表达式或查询表达式中使用ref或out参数“c”

这是我的密码:

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中使用
ref
out
参数

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

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

正如其他答案中所建议的,您必须在方法中本地复制ref变量。之所以必须这样做,是因为lambdas/linq查询会更改它们捕获的变量的生存期,从而导致参数的生存期长于当前方法帧,因为在方法帧不再位于堆栈上之后,可以访问该值

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

作为旁白:a)我建议避免使用公共字段;b) 我建议避免可变结构;c) 如果您发现自己在结构中使用了大量的
ref
,那么您应该使用一个类来代替它吗?(它们远不是等价的,但是如果你使用<代码> REF 避免复制的性能命中,那么这绝对是一件值得考虑的事情)。