【问题标题】:Not understanding variable scope in C# - methods access publics? [duplicate]不理解 C# 中的变量范围 - 方法访问公共? [复制]
【发布时间】:2016-05-27 23:00:29
【问题描述】:

所以我是 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 变量和成员对其他 static 成员可见。这里 Main 是静态的,但 isNegativeinstance 成员而不是 静态一个..

标签: c# variables scope


【解决方案1】:

您应该能够通过将变量声明为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();
        }
    }
}

【讨论】:

    【解决方案2】:

    变量不是类范围的吗?

    是的,他们是。

    如果你看一下你的主要声明:

    static void Main()
    

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

    因此,要纠正您的问题,请将您的 isnegative 变量声明为 static 或在 main.xml 中声明它。你应该没事;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 2014-09-30
      • 2017-11-03
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多