2017-02-09 85 views
0

我正試圖在創建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(); 
    } 
} 

回答

0

安德烈正確地指出的那樣,「構造」 public HighScores()當你創建一個新的HighScores對象就像你有下面被調用。

HighScores David = new HighScores() { Name = "David", Score = 88 }; 

不幸的是,性能NameScore尚未初始化。既然是「構造」簡單地傳遞變量,你想低於正常構造:

HighScores David = new HighScores("David", 88); 

然後設置匹配的簽名在HighScores「構造」,那麼你可以設置的屬性,它應該按預期工作,但是我同意安德烈,因爲這(寫入文件)應該是一個單獨的方法,而不是「構造函數」的一部分希望是有道理的。

public HighScores(string name, int score) { 
    Name = name; 
    Score = score; 
    using (FileStream fileStream = File.OpenWrite(path)) { 
    StreamWriter writer = new StreamWriter(fileStream); 
    writer.Write($"{Name} : {Score} \n"); 
    writer.Close(); 
    } 
} 

+0

好點。我曾認爲初始化程序與構造函數同時運行,但它們之後運行。 – DRockClimber

1

我認爲問題在於構造函數在代碼中的任何「sets」之前運行。在代碼中(在構造函數中,在屬性集中)設置斷點並使用Step Into,可能有助於查看所有代碼的運行順序。

因此,不是在構造函數中寫入值,而是重構變成一種實際的方法。

更改的行

public HighScores() 

public void SaveScores() 

然後添加行之後,你的 「新」 你的對象。

David.SaveScores(); 

這應該工作。

我也會考慮利用using/Dispose模式。

using (var fileStream = File.OpenWrite(path)) 
{ 
    // do stuff 
} 
// dotNet will be sure to call Dispose and clean up the fileStream. 
+0

不錯的選擇,謝謝! – DRockClimber