指標 PointerPlayground2 樣本

來源:互聯網
上載者:User
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;        }    }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.