不了解 C# 中的变量作用域 - 方法访问公共



所以我对C#很陌生,我的大部分编程经验实际上来自多年的PHP工作。据我所知,我已经在我的类中正确声明了我的变量。然而,在我的 Main 方法中,我收到编译器错误 CS0120,即"isnegative"变量在当前上下文中不存在。

变量不是类范围的吗?

namespace ConsoleApplication1
{
class Program
{
    public int isnegative;
    static void Main()
    {
        isnegative = 0;
        for (int i; i = 0; i < 10; i++;)
        {
            if (isnegative == 0)
            {
                i = i;
                isnegative = 0;
            }
            else
            {
                i = i * (-1);
                isnegative = 1;
            }
            Console.WriteLine(i);
        }
    }
}

您应该能够通过使变量声明static来更正问题(与Main方法相同)。

public static int isnegative;

但是你写for语句的方式也存在一些问题。 以下更改将允许程序正常运行:

namespace ConsoleApplication1
{
    class Program
    {
        public static int isnegative;
        static void Main()
        {
            isnegative = 0;
            for (int i = 0; i < 10; i++)
            {
                if (isnegative == 0)
                {
                    i = i;
                    isnegative = 0;
                }
                else
                {
                    i = i*(-1);
                    isnegative = 1;
                }
                Console.WriteLine(i);
            }
            Console.ReadLine();
        }
    }
}

变量不是类范围的吗?

是的,他们是。

如果您查看您的主要声明:

static void Main()

您正在使用静态方法。静态方法只能使用静态类变量。因为它们可以在没有任何实例的情况下调用,而不是需要实例存在的非静态变量。

因此,要纠正您的问题,请将您的 is 负变量声明为静态或在 main 中声明它。你应该没事;)