Csharp/CSharp Tutorial/Data Type/Boxing Unboxing

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

A boxing/unboxing example.

<source lang="csharp">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); 
 } 

}</source>

10

Boxing makes it possible to call methods on a value!

<source lang="csharp">using System;

class MainClass {

 public static void Main() { 

   Console.WriteLine(10.ToString()); 

 } 

}</source>

10

Boxing occurs when passing values

<source lang="csharp">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; 
 } 

}</source>

Here is x: 10
Here is x squared: 100

Change the value after boxing

<source lang="csharp">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);
  }

}</source>

i: 10, io: 10
i: 12, io: 10
i: 12, io: 15

Illustrate automatic boxing during function call

<source lang="csharp">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());
 }
 

}</source>

***** Calling Foo() *****
System.Int32
99
Value of o is: 99
Int32