2014-12-24 46 views
-1

如標題所述「並不發送從一個類的實例具有通過參考將其發送相同的效果」從類發送一個實例是與由參考發送

例如

FillStudentInformation(student); 

具有效果相同

FillStudentInformation(ref student);  

我是否期望這兩個實例都會以相同的方式被這個調用改變。

注:FillStudentUnformation是一種無效的方法

+1

它取決於方法的實現。我認爲你應該閱讀下面的內容:http://msdn.microsoft.com/en-us/library/14akc2c7.aspx – Vlad

+0

不可以。你只能通過第一次調用修改學生屬性,同時可以重新分配學生到另一個學生實例第二個電話 –

+0

你應該閱讀這篇文章:http://www.albahari.com/valuevsreftypes.aspx – MUG4N

回答

0

如果我假設學生是類的對象(引用類型),那麼不應該期望兩者都是不同的東西。它也取決於你在內部做什麼。

在第一種方法

void Main() 
{ 
    Student student = new Student(); 
    FillStudentUnformation(student); 
    Console.WriteLine(student.Name); // Here you will not get name 
    FillStudentUnformationRef(ref student); 
    Console.WriteLine(student.Name); // you will see name you have set inside method. 
} 

vodi FillStudentUnformation(Student student) 
{ 
    //If here if you do 
    student = new Student(); 
    student.Name = "test"; // This will not reflect outside. 
} 

vodi FillStudentUnformationRef(ref Student student) 
{ 
    //If here if you do 
    student = new Student(); 
    student.Name = "test ref"; // This will not reflect outside. 
} 

所以,當我們通過引用類型的方法將通過引用複製到該變量。所以當你用new更新這個變量時,它會更新那個變量引用而不是實際的變量引用。

在第二種方法中,它會傳遞實際的引用,所以當你更新它時會影響對象的實際參考。

更多的:http://msdn.microsoft.com/en-IN/library/s6938f28.aspx

+0

爲什麼在第一個我不會得到名字?我需要了解請 – Miral

+0

你是對的,但我需要理解爲什麼?因爲我認爲在你發送當前地址我們在 – Miral

+0

非常感謝:) – Miral

1

的主要區別是,如果你這樣做的方法中:

student = new Student(); 

在第二種情況下,你會改變外的學生對象方法(不是在第一種情況下)。

使用像:

student.Name = 'John Doe'; 

將努力上是相同的。

但是,您應該儘量避免參考,因爲它會導致更多的副作用和更低的可測試性。