如何将静态数组的元素传递给非静态方法?

时间:2013-03-02 14:46:46

标签: c# static

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

我该怎么做?

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

1 个答案:

答案 0 :(得分: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吗?