2013-12-18 54 views
0

請看下面的代碼。我不能糾正的是,當我們創建類的對象Student命名爲objStudent1,我們設置兩個值名稱和卷號,現在它持有的價值對象的範圍和對象在對象類型上的操作

  • 名稱:STUDENT2
  • 卷號:222

現在我們把這個對象傳遞給一個名爲ChangeName作爲參數,並在此參數的名稱是objStudent2功能,我們再次設置相同的值,現在它持有的價值

  • 名稱:學生三
  • 卷號:333

,然後我們通過設置爲null值objStudent2對象。

執行完整功能ChangeName後,它將打印從函數中設置的值,這些值將從對象objStudent1打印出來。

對數據成員進行的修改是反映,但null不反映在同一對象上的函數之外。

namespace TestApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Student objStudent1 = new Student(); 
      objStudent1.Name = "Student2"; 
      objStudent1.RollNumber = 222; 
      ChangeName(objStudent1); 
      System.Console.WriteLine("Name-" + objStudent1.Name); 
      System.Console.WriteLine("Roll Number-" + objStudent1.RollNumber); 
      System.Console.Read(); 
     } 

     private static void ChangeName(Student objStudent2) 
     { 
      objStudent2.Name = "Student3"; 
      objStudent2.RollNumber = 333; 
      objStudent2 = null; 
     } 
    } 

    class Student 
    { 
     public string Name = "Student1"; 
     int _RollNumber = 111; 

     public int RollNumber 
     { 
      get { return _RollNumber; } 
      set { _RollNumber = value; } 
     } 
    } 
} 

請告訴我這裏發生了什麼事!

我完全困惑!

回答

0

請注意,objStudent1和objStudent2都是對同一個對象的引用。即使在您清除objStudent2引用後,您仍然擁有objStudent1引用。該物體仍然存在。然後你使用objStudent1引用來打印出成員。

0

您的引用變量只不過是您數據實際存在的某些內存位置的引用。

例如:

// this allocates some memory space for your instance/object 
new Student(); 

//this line also does allocates some memory space but the difference is it has got some reference/agent to access that memory location. 
Subject obj = new Student(); 

//This block has obj and obj1. Both obj and obj1 acts almost like agent/broker to that specific memory location. The line 2 does not mean it is separate object/ memory location but its just another reference to the same memory location. 
Subject obj = new Student(); 
Subject obj1 = obj; 

//In 3rd line of this block, you are not nullifying the memory location but you are just trying to nullify the reference alone.It does not make any disturbance to that memory location and its contents. 
Subject obj = new Student(); 
Subject obj1 = obj; 
Obj1=null; 

// This still will work because this reference to that memory location is not nullified. 
Obj.getXXXX(); 

希望這是有益!