我正試圖在創建HighScores對象的那一刻寫入文件。我試圖使用Name和Score屬性作爲文件的文本,但它們似乎分別爲null和0,即使我初始化了該對象。所以我的問題是爲什麼它不寫「大衛:88」?使用屬性寫入文件
static void Main(string[] args)
{
HighScores David = new HighScores() { Name = "David", Score = 88 };
}
class HighScores
{
public string Name { get; set; }
private int score;
public int Score
{
get
{
if (score < 50)
{
return 0;
}
return score;
}
set
{
score = value;
}
}
public HighScores()
{
// Opening and writing to the file
FileStream fileStream = File.OpenWrite(path);
StreamWriter writer = new StreamWriter(fileStream);
writer.Write($"{Name} : {Score} \n");
writer.Close();
}
}
好點。我曾認爲初始化程序與構造函數同時運行,但它們之後運行。 – DRockClimber