2014-12-13 38 views
0

爲什麼i在我將它傳遞給方法時沒有改變?方法調用後i的值爲0,但該方法仍然返回101瞭解C#中的方法機制?

class Program 
{ 
    static void Main(string[] args) 
    { 
     int i = 0; 
     Console.WriteLine("Before static method running i={0}", i); 
     int c= SampleClass.ExampleMethod(i); 
     Console.WriteLine("i={0} - Static method return c={1}",i,c); 
    } 
} 

class SampleClass 
{ 
    public static int ExampleMethod(int i) 
    { 
    i= 101; 
    Console.WriteLine("Inside static method i={0}",i); 
    return i; 
    } 
} 

回答

3

簡短的答案是......我沒有真正傳遞給你的班級功能。我的副本已發送。你必須明確告訴C#發送內存中的實際值而不是副本。你使用「ref」關鍵字來做到這一點。在這個例子中...我...改變

class Program 
{ 
    static void Main(string[] args) 
    { 
     int i = 0; 
     int c = SampleClass.ExampleMethod(ref i); Console.WriteLine("i={0} - c={1}", i, c); 
     Console.ReadLine(); 
    } 

} 

class SampleClass 
{ 
    public static int ExampleMethod(ref int i) 
    { 
     i = 101; 
     return i; 
    } 
} 
+0

謝謝你的回答。 – 2014-12-13 03:55:24

5

在C#,值類型(int S,double S等,由值來傳遞,參考)

爲了修改的i值,則必須使用ref關鍵字。

class Program 
{ 
    static void Main(string[] args) 
    { 
     int i = 0; 
     int c= SampleClass.ExampleMethod(ref i); 
     Console.WriteLine("i={0} - c={1}",i,c); 
    } 
} 

class SampleClass 
{ 
    public static int ExampleMethod(ref int i) 
    { 
     i = 101; 
     return i; 
    } 
} 

通常,最好不要使用ref,而是返回單個值。雖然在這種情況下,你的意圖並不清楚,所以去做一些有用的事。

+0

確定的,但我覺得我缺少成才,我無法理解comprehensively.Does方法參數我只能住在法,這是真的還是假的? – 2014-12-13 03:29:51

+0

使用ref關鍵字,實際指向變量'i'的指針被傳遞,而通常它會通過一個「拷貝」 – Cyral 2014-12-13 03:50:46

+0

謝謝你的回答。 – 2014-12-13 03:56:19