下面的代码段并不是对变量(int)winTemp
和playerWIn
求和。我在验证createXML()
之前通过打印到屏幕验证了两个变量都分配了正确的值。我的理论是,你不能在创建新的XELEMENT时评估方程式。任何人都可以验证这个吗?
new XElement("playerWin", (int)winTemp + playerWin),
如果我在XElement
之外执行此操作,就像saveXML()
中的注释行一样,它会按预期工作。
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace Testing_LINQ_to_XML
{
class Program
{
static void Main()
{
Player p = new Player();
p.readXML();
p.toScreen();
p.saveXML();
p.readXML();
p.toScreen();
p.Exit();
}
}
public class Player
{
public string path;
public string playerName;
public int playerWin = 10;
public int playerLoss = 1;
public int playerTie = 0;
public int winTemp;
public int lossTemp;
public int tieTemp;
public Player()
{
Console.WriteLine("Enter player Name...");
playerName = Console.ReadLine();
Console.WriteLine("n: " + playerName);
getPath();
Console.WriteLine("p: " + path);
Console.ReadLine();
}
public string getPath()
{
path = (@"..\XML Saves\" + playerName + ".xml");
return path;
}
public void toScreen()
{
Console.WriteLine("\nYour Record Is:\n");
Console.WriteLine("Wins: " + playerWin);
Console.WriteLine("Losses: " + playerLoss);
Console.WriteLine("Ties: " + playerTie);
}
public void saveXML()
{
if (File.Exists(path))
{
readXML();
File.Delete(path);
//playerWin = (int)winTemp;
//playerLoss = (int)lossTemp;
//playerTie = (int)tieTemp;
createFile();
}
else
{
createFile();
}
}
public void createFile()
{
XDeclaration _obj = new XDeclaration("1.0", "utf-8", "");
XNamespace gameSaves = "gameSaves";
XElement fileNew = new XElement("Root",
new XElement("Player",
new XElement("playerName", playerName),
new XElement("Stats",
new XElement("playerWin", (int)winTemp + playerWin),
new XElement("playerLoss", (int)lossTemp + playerLoss),
new XElement("playerTie", (int)tieTemp + playerTie))));
fileNew.Save(path);
Console.WriteLine("Save created: " + path);
}
public void readXML()
{
if (File.Exists(path))
{
var winTemp = new XElement("playerWin", playerWin);
var lossTemp = new XElement("playerLoss", playerLoss);
var tieTemp = new XElement("playerTie", playerTie);
}
else
{
Console.WriteLine("\nYou don't have any stats to show yet. Get playing!!!");
}
}
public void Exit()
{
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
}
}
XML输出:
<Root>
<Player>
<playerName>Name</playerName>
<Stats>
<playerWin>10</playerWin>
<playerLoss>1</playerLoss>
<playerTie>0</playerTie>
</Stats>
</Player>
</Root>
答案 0 :(得分:0)
本地范围的winTemp
变量隐藏了实例变量(在readXML()
方法内)。因此,winTemp
实例变量根本没有设置,并且在添加时保持默认值,即0。