无法在匿名方法中使用ref或out参数 [英] Cannot use ref or out parameter inside an anonymous method
问题描述
如果有人可以解决我的问题,我在c#中的代码有问题.
I have a problem with my code in c# if someone could help resolve my problem.
在一个函数中,我正在解析Xml文件并将其保存到结构中.
In a function I am parsing a Xml file and saving it to a struct.
然后我尝试从具有特定节点ID的结构中检索一些信息,并且我的代码失败
Then I try to retreive some info from said struct with a specific node id and my code fails with
不能在匿名方法,lambda表达式或查询表达式中使用ref或out参数'c'"
"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;
}
推荐答案
好吧,您不能在匿名方法或lambda中使用ref
或out
参数,就像编译器错误指出的那样
Well, you're not allowed to use a ref
or a out
parameter in an anonymous method or a lambda, just as the compiler error says.
相反,您必须将ref
参数中的值复制到局部变量中并使用该变量:
Instead you have to copy the value out of the ref
parameter into a local variable and use that:
var nodeId = c.NodeID;
var coordinates = from r in xdoc.Descendants("move")
where int.Parse(r.Attribute("id").Value) == nodeId
...
这篇关于无法在匿名方法中使用ref或out参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!