我有一个静态数组,我需要将它的任意元素传递给非静态方法.
我怎么做?
public class MyClass
{
public static int[] staticArray = { 3, 11, 43, 683, 2731 };
public void SomeMethod(int value)
{
//...stuff...
}
public static void staticMethod()
{
SomeMethod(staticArray[2]); //error here
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试这样的东西时,我得到了错误An object reference is required for the non-static field, method, or property.
您的代码很好,但是'An object reference is required for the non-static field, method, or property'当您尝试调用instance方法或访问类的实例以外的非静态字段/属性时,例如来自静态方法.例如:
class MyClass
{
private int imNotStatic;
public static void Bar()
{
// This will give you your 'An object reference is required` compile
// error, since you are trying to call the instance method SomeMethod
// from a static method, as there is no 'this' to call SomeMethod on.
SomeMethod(5);
// This will also give you that error, as you are calling SomeMethod as
// if it were a static method.
MyClass.SomeMethod(42);
// Again, same error, there is no 'this' to read imNotStatic from.
imNotStatic = -1;
}
public void SomeMethod(int x)
{
// Stuff
}
}
Run Code Online (Sandbox Code Playgroud)
确保您没有执行上述操作之一.你确定你是SomeMethod从构造函数调用的吗?