c#中非静态字段的对象引用

kaw*_*ade 4 c# reference object

我在c#中创建了一个函数:

public void input_fields(int init_xcor, int init_ycor, char init_pos, string input)
{
    char curr_position = 'n';           
    foreach (char c in input)
    {           
        if (c == 'm')
        {
            Move mv = new Move();
            if (curr_position == 'e' || curr_position == 'w')
            {
                init_xcor = mv.Move_Step(curr_position, init_xcor, init_ycor);
            }
            else
            {
                init_ycor = mv.Move_Step(curr_position, init_xcor, init_ycor);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我把这个函数称为:

input_fields(init_xcor, init_ycor, init_pos, input);
Run Code Online (Sandbox Code Playgroud)

但是在调用它时会出错:

非静态字段,方法或属性'TestProject.Program.input_fields(int,int,char,string)'xxx\TestProject\Program.cs需要对象引用23 17 TestProject

我不想让函数静态,因为我还要进行单元测试..

我该怎么办?...请帮帮我.

Jam*_*xon 7

您必须创建包含此方法的类的实例才能访问该方法.

你不能简单地以你正在尝试的方式执行方法.

MyClass myClass = new MyClass();
myClass.input_fields(init_xcor, init_ycor, init_pos, input);
Run Code Online (Sandbox Code Playgroud)

您可以将方法创建为静态,以便您可以在不实例化对象的情况下访问它们,但是仍然需要引用类名.

public static void input_fields(int init_xcor, int init_ycor, 
                                                  char init_pos, string input)
Run Code Online (Sandbox Code Playgroud)

然后

MyClass.input_fields(init_xcor, init_ycor, init_pos, input);
Run Code Online (Sandbox Code Playgroud)