2017-10-06 26 views
-2

我正在開發一個小型天氣應用程序,它使用openweathermap api,它幾乎可以工作。但是這個將城市名稱保存到文本文件的代碼塊不起作用。任何人都可以幫忙不是指具體的類c#WPF

這是調用函數是在MainWindow.Xaml.cs

private void setCurrentCityButton_Click(object sender, RoutedEventArgs e) 
{ 
    CurrentCity.UpdateCurrentCity(); 
} 

這就是所謂的功能是在CurrentCity.cs

AllWeather _allWeather = new AllWeather(); 
//Update Current City to a text file using SteamWriter 
static public void UpdateCurrentCity() 
{   
    using (StreamWriter str = new StreamWriter("currentCity.txt")) 
    { 
     str.WriteLine("Test");//This works fine so no issue with rest 
     str.WriteLine(Convert.ToString(_allWeather.name));//code runs but doesn't get the required name from the AllWeather Class 
    } 
} 

的AllWeather類:

public class AllWeather 
{ 
    public Coord coord { get; set; } 
    public Weather[] weather { get; set; } 
    public string _base { get; set; } 
    public Main main { get; set; } 
    public int visibility { get; set; } 
    public Wind wind { get; set; } 
    public Clouds clouds { get; set; } 
    public int dt { get; set; } 
    public Sys sys { get; set; } 
    public int id { get; set; } 
    public string name { get; set; } 
    public int cod { get; set; } 
} 
+0

*不起作用*並沒有真正描述錯誤,代碼/消息也將有所幫助。無論如何,是'AllWeather _allWeather = new AllWeather()'這一行嗎?意思是,它在CurrentCity類的構造函數中嗎?有關更多信息,您可以顯示「AllWeather」類的部分/全部實現。 –

+0

@KeyurPATEL,對不起,我的壞AllWeather類是一個JSON轉換類,並且包含天氣細節。我試圖從該計劃的其他部分獲取該城市的名稱。下面的代碼不會顯示錯誤,但不會將城市的名稱寫入上述文本文件 str.WriteLine(_allWeather.name); 它仍在工作並用空白替換任何輸入的文本,城市名稱不是從AllWeather類中提取的。即使試過放置 AllWeather _allWeather = new AllWeather();裏面的方法相同的結果 –

+0

你可以使用調試模式,並在str.WriteLine(「Test」)行後面添加一個斷點並檢查'_allWeather'變量以確保它有一個名字嗎?替代方案是'Console.WriteLine(_allWeather.name);'。 –

回答

0

如果問題實際上是AllWeather類和它的構造,你可以只需在主類中創建它,並將其添加作爲參數的函數:

private void setCurrentCityButton_Click(object sender, RoutedEventArgs e) 
{ 
    //something like var _allWeather = JsonConvert.DeserializeObject<AllWeather>(response); 
    CurrentCity.UpdateCurrentCity(_allWeather); 
} 

而在你的其他類:

static public void UpdateCurrentCity(AllWeather _allWeather) 
{   
    using (StreamWriter str = new StreamWriter("currentCity.txt")) 
    { 
     str.WriteLine(Convert.ToString(_allWeather.name)); 
    } 
}