2015-04-17 270 views
2

如果有人可以帮助解决我的问题,我在c#中的代码有问题。不能在匿名方法中使用ref或out参数

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

然后我尝试中检索一些信息与所述与特定的节点ID结构与

“不能使用ref或out参数‘C’匿名方法,lambda表达式或查询在我的代码失败表达”

这里是我的代码:

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; 
} 
+3

另一方面:a)我建议避开公共领域; b)我建议避免可变结构; c)如果你发现自己在一个结构中使用'ref',或许你应该有一个类呢? (他们远非等价,但如果你使用'ref'来避免复制的性能打击,那肯定是要考虑的事情。) –

+0

[Mutable structs is evil](http://stackoverflow.com/questions)/441309 /为什么 - 是 - 可变-结构邪) – juharr

回答

6

好,你不许匿名方法或λ使用refout参数,就像编译器错误说。

相反,你必须到值了ref参数复制到一个局部变量和使用:

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

你应该拉ID的检索出来的anonymo的我们的方法:

var nodeId = c.NodeID; 

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

在其他的答案建议你有裁判变量在方法本地复制。你必须这样做的原因是因为lambdas/linq查询改变了它们捕获的变量的生命周期,导致参数比当前的方法帧寿命更长,因为可以在方法帧不再在堆栈上之后访问该值。

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

相关问题