C# has scopes. An item within a scope can see everything in the scopes that contain it, but outer scopes can't see within inner scopes. You can read about scopes here.
Take your example:
if (input == "create: archer")
{
Archer iArcher = new Archer();
iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
}
iArcher
is in the scope of your if
statement, so code outside that if statement can't see it.
To resolve this, move the definition or iArcher
outside the if statement:
Archer iArcher = new Archer();
if (input == "create: archer")
{
iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
}
if (input == "property: archer")
{
Console.WriteLine(iArcher.getProp());
}
Note that this now leaves you with another problem: input
cannot be both "create: archer" and "property: archer".
One solution might be to move reading user input inside a loop, while keeping iArcher
outside that loop:
Archer iArcher = new Archer();
string input = null;
while ((input = Console.ReadLine()) != "exit")
{
if (input == "create: archer")
{
iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
}
else if (input == "property: archer")
{
Console.WriteLine(iArcher.getProp());
}
}
To exit the loop simply type "exit" as the input.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…