2017-06-13 80 views
0

填充列表我有這些類:從另一個類

class Game 
    { 
     public List<Participant> Participants = new List<Participant>(); 
    } 

class Participant 
    { 
     public int ChampionId { get; set; } 
     public string SummonerName { get; set; } 
     public int SummonerId { get; set; } 
    } 

public class APICalls 
    { 
     //private Game game; 

     private string GetResponse(string url) 
     { 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 

      WebResponse response = request.GetResponse(); 

      using (Stream responseStream = response.GetResponseStream()) 
      { 
       StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); 
       return reader.ReadToEnd(); 
      } 
     } 

     public void GetParticipants() 
     { 
      // create a string from the JSON output 
      var jsonString = GetResponse("https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/27528610?api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); 

      // fill the Participants list from the Game class with participants based on the contents of the jsonString variable 
      Game.Participants = JsonConvert.DeserializeObject<Game>(jsonString); 


     } 

    } 

我要填寫與在APICALLS類的GetParticipants方法Game類我與會者列表。我的問題是我無法從這個類訪問列表。

我想將我的所有API代碼保存在一個類文件中,這就是爲什麼我創建了這個類。

我在做什麼錯?

+0

你不能這樣做,因爲你沒有你的'Game'類的實例。一次只能有一個「遊戲」嗎?那麼也許你可以讓'Game'成爲所謂的Singleton。 –

+0

我建議你的函數有一個返回類型,例如''Public List GetParticipants()',這樣你可以在任何你想要的地方聲明一個'APICalls'的實例,並使用'GetParticipants()''方法手動分配值。 –

回答

2

無論是創建Game的對象,是指使用game.ParticipantsParticipants如下圖所示:

Game game = new Game(); 
game.Participants = JsonConvert.DeserializeObject<Game>(jsonString); 

或者

讓與會者列表中靜:

class Game 
{ 
    public static List<Participant> Participants = new List<Participant>(); 
} 

,並訪問Participants列表它直接使用Game.Participants

+0

我只會在程序運行時使用1個遊戲,直到它再次停止。在這種情況下,你會建議讓參與者列表是靜態的嗎?目前我正在傾向於此。 – FastCow

+0

雅。你可以把它變成靜態的。就像Tim Schmelter所說,如果你有多個線程,你可能會遇到問題。 – Abhishek

3

您需要Game類的實例,以使用它的(非靜態)字段:

var game = new Game(); 
game.Participants = JsonConvert.DeserializeObject<Game>(jsonString); 

如果你只想要一個情況下,你可以使場static,那麼你的代碼工作。但請注意,如果多個線程同時訪問該列表,您可能會遇到問題。

1

參與者不是一個靜態屬性。您需要聲明該類的一個實例。您似乎也試圖將JSON解析爲「遊戲」對象,但將其分配給參與者屬性。我假設實際上JSON正在返回一個參與者列表並進行了相應的修改,但情況可能並非如此。

Game game = new Game(); 
game.Participants = JsonConvert.DeserializeObject<List<Participant>>(jsonString); 
+0

是的,JSON返回參與者列表。 – FastCow

+0

好吧,試試按照我的建議進行反序列化。嘗試將列表反序列化爲不同類型的單個對象不太可行。 – ADyson