using System;namespace exercise { class Program { static unsafe void Main(string[] args) { //PointerPlayground2 該樣本介紹指標的算術,以及結構指標和類成員指標。開始時,定義一個結構CurrencyStruct, //它把貨幣值表示為美元和美分,再定義一個等價的類CurrencyClass: //查看儲存在棧中的項的地址 Console.WriteLine("Szie of CurrencyStruct sturct is " + sizeof(CurrencyStruct)); CurrencyStruct amount1, amount2; CurrencyStruct* pAmount = &amount1; long* pDollars = &pAmount->Dollars; byte* pCents = &(pAmount->Cents); Console.WriteLine("Address of amount1 is 0x{0:X}", (uint)&amount1); Console.WriteLine("Address of amount2 is 0x{0:X}", (uint)&amount2); Console.WriteLine("Address of pAmount is 0x{0:X}", (uint)&pAmount); Console.WriteLine("Address of pDollars is 0x{0:X}", (uint)&pAmount); Console.WriteLine("Address of pCents is 0x{0:X}", (uint)&pCents); pAmount->Dollars = 20; *pCents = 50; Console.WriteLine("amount1 contains " + amount1); //查看儲存在堆中的項的地址 Console.WriteLine("\nNow with classes"); //now try it out with classes CurrencyClass amount3 = new CurrencyClass(); fixed(long* pDollars2 = &amount3.Dollars) fixed(byte* pCents2 = &(amount3.Cents)) { Console.WriteLine("amount3,Dollars has address 0x{0:X}", (uint)pDollars2); Console.WriteLine("amount3.Cents has address 0x{0:X}", (uint)pCents2); *pDollars2 = -100; Console.WriteLine("amount3 conteans " + amount3); } } } internal struct CurrencyStruct { public long Dollars; public byte Cents; public override string ToString() { return "$" + this.Dollars + "." + this.Cents; } } internal class CurrencyClass { public long Dollars; public byte Cents; public override string ToString() { return "$" + this.Dollars + "." + this.Cents; } }}