2013-03-02 56 views
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

+3

上面的代碼編譯(如果你用'// ...東西......替換'......東西......' – 2013-03-02 14:51:25

+1

你的代碼在LinqPad中可以正常工作,你也必須簡化你的測試很多 – 2013-03-02 14:51:27

+1

該代碼編譯完美罰款..粘貼其餘的..錯誤必須在其他地方...東西....或某處... – Matt 2013-03-02 14:51:47

回答

6

您的代碼原樣沒問題,但是當您嘗試調用instance方法時,會出現'An object reference is required for the non-static field, method, or property',或者在靜態方法中訪問非類的實例的非靜態字段/屬性。例如:

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

+0

我似乎正在做... PLZ看我編輯的原始帖子。那麼,如何在沒有錯誤的情況下做我所需要的?戴夫 – davecove 2013-03-02 15:36:55

+0

你不能,'SomeMethod'需要是靜態的,你可以從靜態方法調用它。請刷新靜態方法和實例方法之間的區別,希望能夠讓您深入瞭解解決實際問題的正確方法。 – Bort 2013-03-02 15:42:56

+0

但是,請注意,從'SomeMethod'內部,您可以訪問'staticArray',這意味着代替'// stuff'您可以編寫'int value = staticArray [2];' – Bort 2013-03-02 15:44:57