0
我已經花了幾天的時間試圖解決這個問題,希望你能幫上忙,我對c#很陌生。無法在另一個方法中訪問字符串
下面是我的控制檯應用程序的一部分,兩種不同的方法是在他們自己的獨立計時器中以不同的速度運行,所以他們不能使用相同的方法。我正在使用通過httpclient發送json的JSON.net/JObject。
我試圖從一個不同的方法來訪問的
JObject Grab = JObject.Parse(httpResponse(@"https://api.example.jp/json.json").Result);
string itemTitle = (string)Grab["channel"]["item"][0]["title"];
的結果,使用此代碼
Console.WriteLine(itemTitle);
我已經嘗試了很多不同的方式,但都沒有成功。 以下是關於Json.net的完整代碼部分。
namespace ConsoleApplication3
{
internal class Program
{
...other code
public static async Task<string> httpResponse(string url)
{
HttpClientHandler httpHandler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var httpClient = new HttpClient(httpHandler))
return await httpClient.GetStringAsync(url);
}
public static void JSONUpdateTimer(object sender, ElapsedEventArgs e)
{
JObject Grab = JObject.Parse(httpResponse(@"https://api.example.jp/json.json").Result);
string itemTitle = (string)Grab["channel"]["item"][0]["title"];
Console.WriteLine(itemTitle);
JSONUpdate.Interval = JSONUpdateInterval();
JSONUpdate.Start();
}
public static void SecondTimer(object source, ElapsedEventArgs e)
{
Console.WriteLine(itemTitle);
...other Commands using "itemTitle"
}
}
}
我有一種不好的感覺,我錯過了那麼明顯的事情,如果它指出我會面對手掌。但我會感謝任何幫助。
非常感謝你,我花了這麼多時間,我不相信它有多簡單。 – GumboMcGee