I have two classes:
game
element
I want to be able to define an array of element objects in a game object. When I try this I get the warning message "..is never assigned to, and will always have its default value null"; in the local variables in the debugger I can see that the array exists, but all entries are null. The class Element works as I would expect. If I assign element objects to an array in Main it works, but not when I move the code to the Game constructor.
What am I doing wrong? I'm new to C# so it could be something very b开发者_JAVA百科asic. Code below. Many thanks.
class Element
{
public Element()
{
elements = new List<int>(3);
elements.Add(1);
elements.Add(2);
elements.Add(3);
}
List<int> elements;
public void PrintElement()
{
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Element {0}: {0}", i + 1, elements[i]);
}
}
}
class Game
{
public Game()
{
Element1 = new Element();
Element2 = new Element();
Element3 = new Element();
Element[] ThisGame = new Element[3];
ThisGame[0]= Element1;
ThisGame[1] = Element2;
ThisGame[2] = Element3;
}
public Element[] ThisGame;
private Element Element1;
private Element Element2;
private Element Element3;
public void PrintGameElement(int number)
{
ThisGame[number].PrintElement();
}
}
class Program
{
Game MyGame;
static void Main(string[] args)
{
Game MyGame = new Game();
MyGame.PrintGameElement(2);
Console.Read();
}
}
In Game
, you are re-declaring ThisGame
.
Change
Element[] ThisGame = new Element[3];
to
ThisGame = new Element[3];
Your Game constructor should look like this:
public Game()
{
Element1 = new Element();
Element2 = new Element();
Element3 = new Element();
ThisGame = new Element[3];
ThisGame[0]= Element1;
ThisGame[1] = Element2;
ThisGame[2] = Element3;
}
You need to set the list object to something when you initialize it.
List<int> elements = null;
OR
List<int> elements = new List<int>();
look at this code it may help you to make some order in your code:
Element class :
class Element
{
//property on element to save element data
public string ElementData { get; set; }
public Element(string data)
{
ElementData = data;
}
}
Game class :
class Game
{
//property on Game to save all elements
Element[] Elements { get; set; }
public Game(Element[] elements)
{
Elements = elements;
}
public void PrintGameElements()
{
foreach (var element in Elements)
{
Console.WriteLine(element.ElementData);
}
}
public void PrintElement(int index)
{
Console.WriteLine(Elements[index].ElementData);
}
}
Main function that initialize the array and pass it to the game :
static void Main(string[] args)
{
//initialize the array
var elements = new[]
{
new Element("data x"),
new Element("data y"),
new Element("data z")
};
//pass the elements to the game
var game = new Game(elements);
//print the second element
game.PrintElement(1);
//print all elements
game.PrintGameElements();
Console.ReadKey();
}
}
精彩评论