2014-12-13 34 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