2014-09-21 31 views
0
public class Test 
{ 
    public string Name; 

    public void CallFunctionByObjectRef(Test a) 
    { 
     a.Name = "BCD"; 
     a = null; 
    } 

    public void CallFunctionByObjectRefTORef(ref Test a) 
    { 
     a.Name = "BCD"; 
     a = null; 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 

     Test test = new Test(); 
     test.Name = "ABC"; 
     test.CallFunctionByObjectRef(test); 


     Test test1 = new Test(); 
     test1.Name = "ABC"; 
     test1.CallFunctionByObjectRefTORef(ref test1); 

     Console.WriteLine(test.Name); 
     Console.WriteLine(test1.Name); 
     Console.Read(); 
    } 
} 

在上面調用了兩個函數(使用ref關鍵字,通過對象)。我從他們得到不同的輸出。 但是類對象默認通過引用,爲什麼我得到不同的輸出。通過c中的ref關鍵字調用類對象#

+0

都能跟得上了解更多。參數默認情況下總是按值傳遞。問題是,對於引用類型,被複制和傳遞的值是引用。 – MarcinJuraszek 2014-09-21 06:35:09

+1

作爲輸出得到什麼? – mdebeus 2014-09-21 06:38:47

+1

以下是關於該主題的精彩閱讀 - http://www.yoda.arachsys.com/csharp/parameters.html – 2014-09-21 06:43:16

回答

1
/* Here you are passing pointer to the variable. For example variable test has got memory address 
      * 0X200001. 
      * When you pass test, you are saying that there are two variables that points to 0X200001 (one in main and another in CallFunctionByObjectRef i.e. variable a) 
      * Thus when you are changing the value for a variable to null, you are changing the direction to link with null memory location. 
      * 
      * It is called reference. 
      * When you came back to Main, test variable is still pointing to the memory 0X200001 
      */ 
      Test test = new Test(); 
      test.Name = "ABC"; 

      test.CallFunctionByObjectRef(test); 

      /* 
      * In this case you are saying that create a variable test1 that gives a memory as: 0X200002 
      * Then you are passing a pointer to pointer i.e. you are sending an actual test1 variable. 
      * so whatever you will change here will get impacted in Main. 
      */ 
      Test test1 = new Test(); 
      test1.Name = "ABC"; 

      test1.CallFunctionByObjectRefTORef(ref test1); 

      Console.WriteLine(test.Name); 
      Console.WriteLine(test1.Name); 
      Console.Read(); 

如果你想,那麼你需要從C/C++編程指針的想法,並搜索「參考指針」

+0

謝謝,我喜歡你的答案 – 2014-09-21 08:32:11

0

當使用ref關鍵字時,您將實際的內存位置傳遞給被調用的方法,而不是引用的副本,這是有道理的。

3

就你而言,對類對象的引用是按值傳遞的。

鑑於它接受a如任一值或參考值或參考類型和方法可變a

class A {} 
// or 
struct A {} 

var a = new A(); 

Foo(ref a); 
// or 
Foo(a); 

用戶可以:通過值

  • 通行證引用類型:可以改變對象的變量指的是,你不能改變變量本身。
  • 通過引用傳遞引用類型:可以更改變量引用的對象,可以更改變量本身。
  • 按值傳遞值類型:不能更改變量引用的對象,不能更改變量本身。
  • 通過引用傳遞值類型:您可以更改變量引用的對象,但不能更改變量本身。
1

閱讀Passing Reference-Type Parameters (MSDN)

引用類型不直接包含其數據的變量;它包含對其數據的引用。當按值傳遞引用類型參數時,可以更改引用指向的數據,例如類成員的值。但是,您不能更改引用本身的值;也就是說,不能使用相同的引用爲新類分配內存,並使其保留在塊之外。要做到這一點,請使用ref或out關鍵字傳遞參數。