2017-01-30 81 views
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" 
    } 
} 
} 

我有一种不好的感觉,我错过了那么明显的事情,如果它指出我会面对手掌。但我会感谢任何帮助。

回答

3

在任何方法之外声明一个名为itemTitle的字符串字段作为该类的成员。

internal class Program 
{ 
    static string itemTitle; 
    //other code... 
} 

在你的方法中,不要声明一个新变量,只要引用该字段。

public static void JSONUpdateTimer(object sender, ElapsedEventArgs e) 
{ 
    //... 
    itemTitle = (string)Grab["channel"]["item"][0]["title"]; 
    //... 
} 

在方法中声明的变量在本地作用于该方法,并且不在其外部存在。

+0

非常感谢你,我花了这么多时间,我不相信它有多简单。 – GumboMcGee

相关问题