1

我有一个静态数组,我需要将它的任意元素传递给非静态方法。

我怎么做?

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
    }
}

当我尝试类似的事情时,我得到了错误An object reference is required for the non-static field, method, or property

4

1 回答 1

6

您的代码很好,但是'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
    }
}

确保您没有执行上述任一操作。你确定你是SomeMethod从构造函数调用的吗?

于 2013-03-02T15:01:06.933 回答