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;
}
}
}