2010年3月21日日曜日

値型と参照型

EffectiveC#を読んで、基本に立ち返ってみた。

(参照渡)

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         var val = new Class();  
  6.         var val2 = val;         //参照渡し  
  7.   
  8.         val.MyProperty = 100;  
  9.   
  10.         //100   が表示される  
  11.         Console.WriteLine(val2.MyProperty);  
  12.     }  
  13. }  
  14.   
  15. class Class  
  16. {  
  17.     public int MyProperty { getset; }  
  18. }  

classは参照型であり、代入は参照がコピーされる。なので、 valとVal2の指す実体は同じ。 
image

(値渡)

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         var val = new Struct();  
  6.         var val2 = val;         //値渡し  
  7.   
  8.         val.MyProperty = 100;  
  9.   
  10.         //0   が表示される  
  11.         Console.WriteLine(val2.MyProperty);  
  12.   
  13.     }  
  14. }  
  15.   
  16. struct Struct  
  17. {  
  18.     public int MyProperty { getset; }  
  19. }  

structは値型であり、代入はコピーが作成されるので、valを変更してもval2に影響はない。
image

0 件のコメント: