【问题标题】:C# pointers what does X in the Console.WriteLine signify?C# 指针 Console.WriteLine 中的 X 表示什么?
【发布时间】:2019-12-23 06:53:54
【问题描述】:

我刚刚浏览了 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/pointer-related-operators#pointer-member-access-operator 上的 C# 指针描述并遇到了这个示例:

unsafe
{
    char letter = 'A';
    char* pointerToLetter = &letter;
    Console.WriteLine($"Value of the `letter` variable: {letter}");

    // Look at the end of the following statement
    Console.WriteLine($"Address of the `letter` variable: {(long)pointerToLetter:X}");

    *pointerToLetter = 'Z';
    Console.WriteLine($"Value of the `letter` variable after update: {letter}");
}
// Output is similar to:
// Value of the `letter` variable: A
// Address of the `letter` variable: DCB977DDF4
// Value of the `letter` variable after update: Z

下面语句中的X是做什么的?

Console.WriteLine($"Address of the `letter` variable: {(long)pointerToLetter:X}");

为什么不直接

Console.WriteLine($"Address of the `letter` variable: {(long)pointerToLetter}");

【问题讨论】:

标签: c# .net pointers console-application unmanaged


【解决方案1】:

将 long 格式化为十六进制。您也可以在其后添加一个数字来指定宽度(用前导零填充)

Console.WriteLine($"Address of the `letter` variable: {(long)pointerToLetter:X8}");

--> Address of the `letter` variable: 00001EA4

Console.WriteLine($"Address of the `letter` variable: {(long)pointerToLetter:X}");

相当于

Console.WriteLine(String.Format("Address of the `letter` variable: {0:X}", (long)pointerToLetter));

相当于

Console.WriteLine(String.Format("Address of the `letter` variable: {0}", ((long)pointerToLetter).ToString("X")));

为什么不直接

Console.WriteLine($"Address of the `letter` variable: {(long)pointerToLetter}");

你问.. 好吧,因为它会以 10 为基数而不是十六进制打印内存地址。有关为什么我们用十六进制表示内存地址的详细讨论,请参阅Why are memory addresses are represented using hexadecimal numbers?

【讨论】:

    猜你喜欢
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多