C# 名称“...”在当前上下文中不存在

Bus*_*kie 1 c# syntax-error

我是 C# 新手,我尝试从基础知识开始学习,但我坚持上课。我做了第一个例子来练习,它工作正常,但是当我添加一点复杂性时,我收到错误:

“‘iArcher’这个名字在当前上下文中不存在。”

请帮助解释问题所在并提出正确(且简单)的解决方案。

谢谢!

using System;

namespace Units
{
    class Archer
    {
        public int id;
        public int hp;
        public float speed;
        public float attack;
        public float defence;
        public float range;

        public void setProp(int id, int hp, float sp, float at, float de, float ra)
        {
            this.id = id;
            this.hp = hp;
            speed   = sp;
            attack  = at;
            defence = de;
            range   = ra;
        }

        public string getProp()
        {
            string str = "ID        = " + id +      "\n" +
                         "Health    = " + hp +      "\n" +
                         "Speed     = " + speed +   "\n" +
                         "Attack    = " + attack +  "\n" +
                         "Defence   = " + defence + "\n" +
                         "Range     = " + range +   "\n" ;

            return str;
        }

        static void Main(string[] args)
        {
            string input = Console.ReadLine();

            if (input == "create: archer")
            {
                Archer iArcher = new Archer();
                iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
            }

            if (input == "property: archer")
            {
                Console.WriteLine(iArcher.getProp());    // ERROR!
            }
            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 5

C# 有作用域。范围内的项目可以看到包含它的范围内的所有内容,但外部范围无法看到内部范围内的内容。您可以在此处阅读有关范围的信息。

拿你的例子来说:

if (input == "create: archer")
{
    Archer iArcher = new Archer();
    iArcher.setProp(100, 20, 4f, 8f, 3.5f, 25f);
}
Run Code Online (Sandbox Code Playgroud)

iArcher在您的语句范围内if,因此 if 语句之外的代码看不到它。

要解决此问题,请将定义移至iArcherif 语句之外:

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());
}
Run Code Online (Sandbox Code Playgroud)

请注意,这现在给您留下了另一个问题:input不能同时是“create: archer”和“property: archer”。

一种解决方案可能是将读取用户输入移至循环内部,同时保持iArcher在循环外部:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

要退出循环,只需输入“exit”即可。