如何在for循环中声明变量
foreach (System.Xml.XmlNode xmlnode in node)
{
string AMSListName = xmlnode.Attributes["Title"].Value.ToString();
/* the below assignment should be variable for each iteration */
XmlNode ndViewFields + AMSListName = xmlDoc.CreateNode(XmlNodeType.Element,
"ViewFields", "");
}
Run Code Online (Sandbox Code Playgroud)
我该如何实现这一目标?我希望for循环中的每个值都让xmlnode具有不同的名称.这有可能吗?
使用集合:
List<XmlNode> nodes = new List<XmlNode>();
foreach (System.Xml.XmlNode xmlnode in node)
{
string AMSListName = xmlnode.Attributes["Title"].Value.ToString();
nodes.Add(xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", ""));
}
Run Code Online (Sandbox Code Playgroud)
您可以通过索引或循环访问此列表:
foreach(var node in nodes)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
另一种方法如果名称是标识符,请使用Dictionary:
Dictionary<string, System.Xml.XmlNode> nodeNames = new Dictionary<string, System.Xml.XmlNode>();
foreach (System.Xml.XmlNode xmlnode in node)
{
string AMSListName = xmlnode.Attributes["Title"].Value.ToString();
nodeNames[AMSListName] = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
}
Run Code Online (Sandbox Code Playgroud)
这将替换具有给定名称的已经可用的节点,否则它将添加它.
您可以通过名称访问它:
XmlNode node
if(nodeNames.TryGetValue("Some Name", out node)
{
// ..
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
189 次 |
| 最近记录: |