Csharp/CSharp Tutorial/struct/Box Unbox

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

Box and unbox a struct

using System;
struct EMPLOYEE 
{
  public string name;
  public short deptID;
  public EMPLOYEE(string n, short d)
  {
    name = n;
    deptID = d;
  }
}
class MainClass
{
  public static void Main(string[] args) {
    EMPLOYEE fred = new EMPLOYEE("s",1);
    fred.name = "F";
    object stanInBox = fred;
  
    UnboxThisEmployee(stanInBox);
  }
  public static void UnboxThisEmployee(object o)
  {
    EMPLOYEE temp = (EMPLOYEE)o;
    Console.WriteLine(temp.name);
  }
  
}
F

Box a struct, change its value and unbox it

public interface IModifyMyStruct
{
   int X
   {
      get;
      set;
   }
}
public struct MyStruct : IModifyMyStruct
{
   public int x;
   public int X
   {
      get
      {
         return x;
      }
      set
      {
         x = value;
      }
   }
   public override string ToString()
   {
      return x.ToString();
   }
}
public class MainClass
{
   static void Main()
   {
      MyStruct myval = new MyStruct();
      myval.x = 123;
      object obj = myval;
      System.Console.WriteLine( "{0}", obj.ToString() );
      IModifyMyStruct iface = (IModifyMyStruct) obj;
      iface.X = 456;
      System.Console.WriteLine( "{0}", obj.ToString() );
      MyStruct newval = (MyStruct) obj;
      System.Console.WriteLine( "{0}", newval.ToString() );
   }
}
123
456
456

Box struct to call its implemented interface

public interface IDisplay
{
   void Print();
}
public struct MyStruct : IDisplay
{
   public int x;
   public void Print()
   {
      System.Console.WriteLine( "{0}", x );
   }
}
public class MainClass
{
   static void Main()
   {
      MyStruct myval = new MyStruct();
      myval.x = 123;
      // no boxing
      myval.Print();
      // must box the value
      IDisplay printer = myval;
      printer.Print();
   }
}
123
123