2010年3月27日土曜日

Interfaceは参照型

Interfaceは参照型だったよな。と思い確認。

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.   
  6.         Struct s = new Struct();  
  7.         s.MyProperty = 1;  
  8.   
  9.         Interface i = s;  
  10.         i.MyProperty = 2;  
  11.   
  12.         Interface i2 = i;  
  13.         i2.MyProperty = 3;  
  14.   
  15.         Console.WriteLine("s :{0}", s.MyProperty);  
  16.         Console.WriteLine("i :{0}", i.MyProperty);  
  17.         Console.WriteLine("i2:{0}", i2.MyProperty);  
  18.     }  
  19. }  
  20.   
  21. interface Interface  
  22. {  
  23.     int MyProperty { getset; }  
  24. }  
  25.   
  26. struct Struct : Interface  
  27. {  
  28.     public int MyProperty { getset; }  
  29. }  
結果
image

正解。

つまり、Interface型に代入する際にボックス化が行われているということ。

  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         var val = new Struct();  
  6.         var val2 = new Class();  
  7.   
  8.         Stopwatch sw = Stopwatch.StartNew();  
  9.         for (int i = 0; i < 1000000000; i++)  
  10.         {  
  11.             object obj = val;  
  12.         }  
  13.         Console.WriteLine("struct -> object   :" + sw.Elapsed);  
  14.         sw.Reset();  
  15.         sw.Start();  
  16.         for (int i = 0; i < 1000000000; i++)  
  17.         {  
  18.             Interface obj = val;  
  19.         }  
  20.         Console.WriteLine("struct -> Interface:" + sw.Elapsed);  
  21.         sw.Reset();  
  22.         sw.Start();  
  23.         for (int i = 0; i < 1000000000; i++)  
  24.         {  
  25.             var obj = val;  
  26.         }  
  27.         Console.WriteLine("struct -> struct   :" + sw.Elapsed);  
  28.         sw.Reset();  
  29.         sw.Start();  
  30.         for (int i = 0; i < 1000000000; i++)  
  31.         {  
  32.             Interface obj = val2;  
  33.         }  
  34.         Console.WriteLine("class  -> Interface:" + sw.Elapsed);  
  35.         sw.Reset();  
  36.         sw.Start();  
  37.         for (int i = 0; i < 1000000000; i++)  
  38.         {  
  39.             object obj = val2;  
  40.         }  
  41.         Console.WriteLine("class  -> object   :" + sw.Elapsed);  
  42.         sw.Reset();  
  43.         sw.Start();  
  44.         for (int i = 0; i < 1000000000; i++)  
  45.         {  
  46.             var obj = val2;  
  47.         }  
  48.         Console.WriteLine("class  -> class    :" + sw.Elapsed);  
  49.   
  50.   
  51.     }  
  52. }  
  53.   
  54. interface Interface  
  55. {  
  56.     int MyProperty { getset; }  
  57. }  
  58.   
  59. struct Struct : Interface  
  60. {  
  61.     public int MyProperty { getset; }  
  62. }  
  63.   
  64.   
  65. class Class : Interface  
  66. {  
  67.     public int MyProperty { getset; }  
  68. }  

image

0 件のコメント: