指针转换,C# 编程指南

原文地址:https://msdn.microsoft.com/zh-cn/library/etb4xxec.aspx

隐式转换可能在多种情形下发生,包括调用方法时和在赋值语句中。

隐式指针转换

发件人

目标

任何指针类型

void*

null

任何指针类型

下表显示了这些转换。

显式指针转换

发件人

目标

任何指针类型

所有其他指针类型

sbyte、byte、short、ushort、int、uint、long 或 ulong

任何指针类型

任何指针类型

sbyte、byte、short、ushort、int、uint、long 或 ulong

连续递增该结果直到达到 int 的大小(4 字节),即可显示变量的剩余字节。

C#

  // compile with: /unsafe

C#

  class ClassConvert
{
    static void Main() 
    {
        int number = 1024;

        unsafe 
        {
            // Convert to byte:
            byte* p = (byte*)&number;

            System.Console.Write("The 4 bytes of the integer:");

            // Display the 4 bytes of the int variable:
            for (int i = 0 ; i < sizeof(int) ; ++i)
            {
                System.Console.Write(" {0:X2}", *p);
                // Increment the pointer:
                p++;
            }
            System.Console.WriteLine();
            System.Console.WriteLine("The value of the integer: {0}", number);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}
    /* Output:
        The 4 bytes of the integer: 00 04 00 00
        The value of the integer: 1024
    */