无法使用实例引用访问

时间:2012-10-18 06:28:30

标签: c#

  

可能重复:
  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();
        }
    }

2 个答案:

答案 0 :(得分:2)

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

所以,你有两个选择。

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

  2. Move更改为实例方法。

  3. 我认为选项2是要走的路。正如Jon Skeet指出的那样。更有意义的是Move应该是一个实例方法。

答案 1 :(得分:1)

  

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)
相关问题