PointerPlayaround2.cs
上传用户:lxycoco
上传日期:2022-07-21
资源大小:38457k
文件大小:2k
源码类别:

C#编程

开发平台:

Others

  1. using System;
  2. namespace Wrox.ProCSharp.AdvancedCSharp
  3. {
  4.    public class MainEntryPoint
  5.    {
  6.       public static unsafe void Main()
  7.       {
  8.          Console.WriteLine("Size of Currency struct is " + sizeof(CurrencyStruct));
  9.          CurrencyStruct amount1, amount2;
  10.          CurrencyStruct *pAmount = &amount1;
  11.          long *pDollars = &(pAmount->Dollars);
  12.          byte *pCents = &(pAmount->Cents);
  13.          Console.WriteLine("Address of amount1 is 0x{0:X}", (uint)&amount1);
  14.          Console.WriteLine("Address of amount2 is 0x{0:X}", (uint)&amount2);
  15.          Console.WriteLine("Address of pAmt is 0x{0:X}", (uint)&pAmount);
  16.          Console.WriteLine("Address of pDollars is 0x{0:X}", (uint)&pDollars);
  17.          Console.WriteLine("Address of pCents is 0x{0:X}", (uint)&pCents);
  18.          pAmount->Dollars = 20;
  19.          *pCents = 50;
  20.          Console.WriteLine("amount1 contains " + amount1);
  21.          --pAmount;   // this should get it to point to amount2
  22.          Console.WriteLine("amount2 has address 0x{0:X} and contains {1}", 
  23.             (uint)pAmount, *pAmount);
  24.          // do some clever casting to get pCents to point to cents
  25.          // inside amount2
  26.          CurrencyStruct *pTempCurrency = (CurrencyStruct*)pCents;
  27.          pCents = (byte*) ( --pTempCurrency );
  28.          Console.WriteLine("Address of pCents is now 0x{0:X}", (uint)&pCents);
  29.          Console.WriteLine("nNow with classes");
  30.          // now try it out with classes
  31.          CurrencyClass amount3 = new CurrencyClass();
  32.          fixed(long *pDollars2 = &(amount3.Dollars))
  33.          fixed(byte *pCents2 = &(amount3.Cents))
  34.          {
  35.             Console.WriteLine("amount3.Dollars has address 0x{0:X}", (uint)pDollars2);
  36.             Console.WriteLine("amount3.Cents has address 0x{0:X}", (uint) pCents2);
  37.             *pDollars2 = -100;
  38.             Console.WriteLine("amount3 contains " + amount3);
  39.          }
  40.       }
  41.    }
  42.    struct CurrencyStruct
  43.    {
  44.       public long Dollars;
  45.       public byte Cents;
  46.       public override string ToString()
  47.       {
  48.          return "$" + Dollars + "." + Cents;
  49.       }
  50.    }
  51.    class CurrencyClass
  52.    {
  53.       public long Dollars;
  54.       public byte Cents;
  55.       public override string ToString()
  56.       {
  57.          return "$" + Dollars + "." + Cents;
  58.       }
  59.    }
  60. }