C# Can';t在if()中使用公共类中的静态变量

C# Can';t在if()中使用公共类中的静态变量,c#,mono,rider,C#,Mono,Rider,首先,我是C#的新手 我需要获得一个特定的控制台输入,并且需要在另一个类中使用该变量。所以我有我的Monster.cs和Program.cs源文件 所以这是可行的(仅限于Program.cs): 但这为什么不起作用呢 Monster.cs Program.cs 这段代码有几个问题。我假设您不希望程序在使用字段时像现在这样不断地从控制台读取数据。您可能需要在类的开头提供一个构造函数来分配race的值,如下所示: Monster() { this.race=Console.ReadLine(); }

首先,我是C#的新手

我需要获得一个特定的控制台输入,并且需要在另一个类中使用该变量。所以我有我的
Monster.cs
Program.cs
源文件

所以这是可行的(仅限于
Program.cs
):

但这为什么不起作用呢

Monster.cs Program.cs
这段代码有几个问题。我假设您不希望程序在使用字段时像现在这样不断地从控制台读取数据。您可能需要在类的开头提供一个构造函数来分配race的值,如下所示:

Monster()
{
this.race=Console.ReadLine();
}

或者您必须通过调用代码来分配它。为了做到这一点,然后访问它的值,您需要一个类的实例。您可以这样做:

Monster newMonster=newMonster();
newMonster.race=Console.ReadLine()//仅当没有构造函数时

然后,您可以继续在给定表达式中使用race的值,例如:

if(newMonster.race==“1”){//code here}

但是,如果字段不需要特定于类的值,即跨类实例的值不变,则可以按照@Backs的建议,将race声明为静态字段,如下所示:

公共静态字符串竞赛

这样,您就根本不需要类的
newMonster
实例了。相反,您可以简单地使用调用代码中的以下内容

Monster.race=Console.ReadLine();
如果(Monster.race==“1”){//code here}


但是请注意,您的字符串声明仍然不能将其分配给类中的
Console.ReadLine()

阅读关于静态类和字段的内容:
        string race = Console.ReadLine();

        if (race == "1")
        {
            Console.WriteLine("Typed 1");
        }
        else if (race == "2")
        {
            Console.WriteLine("Typed 2");
        }
        else if (race == "3")
        {
            Console.WriteLine("Typed 3");
        }
        else
        {
            Console.WriteLine("Typed something wrong");
        }
namespace ConsoleSimulation
{
  public class Monster
  {
    public string race = Console.ReadLine();
  }
}
        string race = Console.ReadLine();

    if (Monster.race == "1")
    {
        Console.WriteLine("Typed 1");
    }
    else if (Monster.race == "2")
    {
        Console.WriteLine("Typed 2");
    }
    else if (Monster.race == "3")
    {
        Console.WriteLine("Typed 3");
    }
    else
    {
        Console.WriteLine("Typed something wrong");
    }