【问题标题】:Cannot be accessed with an instance reference [duplicate]无法通过实例引用访问 [重复]
【发布时间】:2012-10-18 06:28:29
【问题描述】:

可能重复:
Why do I get “cannot be accessed with an instance reference” when using teststring.Join but not teststring.Split? (c#)

我不确定代码有什么问题。我尝试谷歌搜索,但没有得到相关信息。

这是我的 for 循环。

          for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j < 5; j++)
                {
                    slide.Move(s, i, j); // this is the problem. 
                }
            }

这是我的移动功能。根据我的说法,我认为我正在按照假设的方式调用该函数,但我无法弄清楚出了什么问题。我是相当新的语言。

         protected static void Move(string s, int x, int y)
    {
        Console.WriteLine("I am in Move function");
        try
        {
            Console.SetCursorPosition(origCol + x, origRow + y);
            Console.Write(s);
        }
        catch (ArgumentOutOfRangeException e)
        {
            Console.Clear();
            Console.WriteLine(e.Message);
        }

        for (int i = 0; i < DEFAULT_SIZE; ++i)
        {
            for (int j = 0; j < DEFAULT_SIZE; ++j)
            {
                    Console.Write("#");
                    Console.Write("\r{0}%   ", i,j);
                    //Console.WriteLine(slider[i, j]);
            }
            Console.WriteLine();
            Console.ReadKey();
        }
    }

【问题讨论】:

    标签: c#


    【解决方案1】:

    Move 是一种静态方法,因此您可以使用ClassName.Move 调用它。

    所以,这里有 2 个选项。

    1. 更改 slide.Move(s, i, j); 以使用类名,而不是实例变量。例如,如果类名Slide,那么您应该使用Slide.Move(s, i, j);

    2. Move更改为实例方法。

    我认为选项 2 是可行的方法。正如乔恩斯基特指出的那样。 Move 应该是一个实例方法更有意义。

    【讨论】:

    • ... 或将Move 方法设为实例方法,当然。它不看起来应该是静态的。
    • for循环在main中,Move函数在类中。所以我还是应该将它与类名而不是实例变量一起使用。
    【解决方案2】:

    protected static void Move(string s, int x, int y)

    静态成员属于类而不是类的实例。要访问它们,请在它们前面加上类的名称

    [ClassName].Move(s, x, y);  //Slide.Move(x, y, z); assuming your class name is Slide
    

    要这样使用它,您需要删除静态修饰符

    protected void Move(string s, int x, int y)
    

    【讨论】:

    • 太棒了。是的,就是这样,这是有道理的。有用。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2014-04-07
    • 1970-01-01
    相关资源
    最近更新 更多