我正在从数据库中检索数据并尝试填充 List<>。那是我的目标。
我目前正在将检索到的数据插入到方法中的变量中,然后尝试将该方法添加到 List<>。
这是我的代码:
public void Select()
{
var sprite = new Sprite();
if (Game.player.inBattle)
{
//Open a connection
databaseCon.Open(); //Works
//Create Command
var cmd = new MySqlCommand(BattleEngine.query, databaseCon); //Works
//Create a data reader and Execute the command
var dataReader = cmd.ExecuteReader(); //Works
try
{
//Read the data and store them in the list
while (dataReader.Read())
{
//Inserts matching Row's first Column attribute into method variable
sprite.id = (dataReader.GetInt32(0));
//Inserts matching Row's second Column attribute into method variable
sprite.identifier = (dataReader.GetString(1));
Console.WriteLine(sprite.id + ": " + sprite.identifier); //Works. Variables are loaded with data
//Fails. Doesn't load the method into the list
Game.sprite.Add(new Sprite());
}
}
catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex);
}
finally
{
if (dataReader != null)
{
//close Data Reader
dataReader.Close();
}
if (databaseCon != null)
{
//close Connection
databaseCon.Close();
}
}
}
}
Console.WriteLine(Game.sprite[0]);
然后我在这个循环之后有一个测试设置,它显示Namespace.Sprite
可能还有其他方法可以做到这一点,但最终我希望用新方法中的每条记录填充列表。通过将其存储在 List<> 中,我可以提取特定信息以供以后使用。
理论上我希望能够做到这一点;
Console.WriteLine("{0}", Game.sprite[0].id);
我以前见过这样做,但我似乎无法复制它。
添加:
public class Game
{
public static Player player;
public static List<Character> sprite;
GameScreens mainMenu = new GameScreens();
GameScreens titleScreen = new GameScreens();
public Game()
{
Console.SetWindowSize(100, 50);
Console.BufferHeight = 50;
Console.BufferWidth = 100;
titleScreen.TitleScreen();
player = new Player();
sprite = new List<Character>();
Player.Initialize(player);
GameLoop();
}
void GameLoop() //Our game loop.
{
mainMenu.MainMenu();
}
}