在C#中的非静态字段对象引用 [英] Object reference for non-static field in c#

查看:273
本文介绍了在C#中的非静态字段对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造了一个函数在C#中为:

I had created a function in c# as:

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);



但同时呼吁它给了一个错误:

but while calling it is giving an error:

的对象引用需要
中的非静态字段,方法或
属性
位TestProject.Program.input_fields(中间体,
INT,CHAR
字符串)xxx\TestProject\Program.cs 23 17 TestProject

An object reference is required for the non-static field, method, or property 'TestProject.Program.input_fields(int, int, char, string)' xxx\TestProject\Program.cs 23 17 TestProject

我不不想让静态的功能,因为我必须做一个单元测试也..

I don't want to make the function static as I have to do an unit test also..

我应该为此做什么? ...
请帮我。

What should I do for this? ... Please help me out.

推荐答案

您必须创建包含此方法的类的实例为了访问方法。

You have to create an instance of the class containing this method in order to access the method.

您不能简单地执行它,似乎你想要的方式方法。

You can't simply execute methods in the way it seems you're trying.

MyClass myClass = new MyClass();
myClass.input_fields(init_xcor, init_ycor, init_pos, input);

您可以创建方法为静态,这样就可以没有对象的实例化但仍可以访问他们,你需要参考的类名。

You can create methods as static so that you can access them without the instantiation of an object however you still need to refer to the class name.

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);

这篇关于在C#中的非静态字段对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆