c#中非静态字段的对象引用
我在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); } } } }
我把这个函数称为:
input_fields(init_xcor, init_ycor, init_pos, input);
但是在调用它时会出错:
非静态字段,方法或属性’TestProject.Program.input_fields(int,int,char,string)’xxx \ TestProject \ Program.cs需要对象引用23 17 TestProject
我不想让函数静态,因为我还要进行unit testing..
我该怎么办? …请帮帮我。
您必须创建包含此方法的类的实例才能访问该方法。
你不能简单地按照你正在尝试的方式执行方法。
MyClass myClass = new MyClass(); myClass.input_fields(init_xcor, init_ycor, init_pos, input);
您可以将方法创建为静态,以便您可以在不实例化对象的情况下访问它们,但是仍然需要引用类名。
public static void input_fields(int init_xcor, int init_ycor, char init_pos, string input)
然后
MyClass.input_fields(init_xcor, init_ycor, init_pos, input);
您必须在此方法所属的类的对象上调用此方法。 所以,如果你有类似的东西:
public class MyClass { public void input_fields(int init_xcor, int init_ycor, char init_pos, string input) { ... } ... }
你必须这样做:
MyClass myObject = new MyClass(); myObject.input_fields(init_xcor, init_ycor, init_pos, input);
由于该函数not static
,因此您需要创建该类的实例以调用该方法,例如,
MyClass cl = new MyClass(); cl.input_fields(init_xcor, init_ycor, init_pos, input);
否则将方法标记为静态
public static void input_fields....
并将其称为MyClass.input_fields(init_xcor,init_ycor,init_pos,input);
从您的错误看起来您正在从main()或静态Program类中的其他静态方法调用您的方法。 简单地将您的方法声明为静态将解决问题:
public static void input_fields(int init_xcor, int init_ycor, char init_pos, string input) ...
但这是一个快速修复,可能不是最佳解决方案(除非您只是简单地进行原型设计或测试function。)如果您计划进一步使用此代码,您的方法应该移动到一个单独的类(静态或不静态)。程序类及其main()函数是应用程序的入口点,而不是应用程序逻辑的唯一位置。