Csharp/CSharp Tutorial/Data Type/Boxing Unboxing

Материал из .Net Framework эксперт
Версия от 12:18, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A boxing/unboxing example.

using System; 
 
class MainClass { 
  public static void Main() { 
    int x; 
    object obj; 
 
    x = 10; 
    obj = x; // box x into an object 
 
    int y = (int)obj; // unbox obj into an int 
    Console.WriteLine(y); 
  } 
}
10

Boxing makes it possible to call methods on a value!

using System; 
 
class MainClass { 
  public static void Main() { 
 
    Console.WriteLine(10.ToString()); 
 
  } 
}
10

Boxing occurs when passing values

using System; 
 
class MainClass { 
  public static void Main() { 
    int x; 
    
    x = 10; 
    Console.WriteLine("Here is x: " + x); 
 
    // x is automatically boxed when passed to sqr() 
    x = sqr(x); 
    Console.WriteLine("Here is x squared: " + x); 
  } 
 
  static int sqr(object o) { 
    return (int)o * (int)o; 
  } 
}
Here is x: 10
Here is x squared: 100

Change the value after boxing

using System;
class MainClass
{
   static void Main()
   {
      int i = 10;           
      object oi = i;        
      
      Console.WriteLine("i: {0}, io: {1}", i, oi);
      
      i  = 12;
      
      Console.WriteLine("i: {0}, io: {1}", i, oi);
      
      oi = 15;
      Console.WriteLine("i: {0}, io: {1}", i, oi);
   }
}
i: 10, io: 10
i: 12, io: 10
i: 12, io: 15

Illustrate automatic boxing during function call

using System;
using System.Collections;
class MainClass
{
  static void Main(string[] args)
  {    
    Console.WriteLine("\n***** Calling Foo() *****");
    int x = 99;
    Foo(x);
  }
  public static void Foo(object o)
  {
    Console.WriteLine(o.GetType());
    Console.WriteLine(o.ToString());
    Console.WriteLine("Value of o is: {0}", o);
    // Need to unbox to get at members of
    // System.Int32.
    int unboxedInt = (int)o;
    Console.WriteLine(unboxedInt.GetTypeCode());
  }
  
}
***** Calling Foo() *****
System.Int32
99
Value of o is: 99
Int32