2014-03-19 49 views
2

我正在學習使用ref,但無法理解,爲什麼我得到一個錯誤?如何使用ref?

class A 
{ 
    public void ret(ref int variable) 
    { 
     variable = 7; 
    } 

    static int Main() 
    { 
     int z = 5; 
     ret(ref z); // Error: Need a reference on object 
     Console.WriteLine(z); // it will be 7 as I understand 
     return 0; 
    } 
} 

回答

9

問題不在於ref參數。這就是ret是一個實例方法,並且不能在不引用該類型的實例的情況下調用實例方法。

嘗試使ret靜:

public static void ret(ref int variable) 
{ 
    variable = 7; 
} 
3

你的方法是不是static.You需要提出的是靜態的是這樣的:

public static void ret(ref int variable) 
{ 
    variable = 7; 
} 
5

你正確使用ref。該錯誤實際上是因爲ret()實例方法,而Main()靜態。使ret()也是靜態的,並且此代碼將按照您的預期進行編譯和工作。

2

由於ret是一種實例方法,如果不創建該類型的對象,則無法訪問它。

嘗試製作方法retstatic methodpublic static void ret(ref int variable)