C#6 字符串插值 + 短格式字符串错误?

Mic*_*ael 5 c# .net-core

C# 6 引入了字符串插值和一种更短的方式来指定格式字符串。

IntPtr ptr = new IntPtr(0xff);

Console.WriteLine(ptr.ToString());      // 255
Console.WriteLine(ptr.ToString("x"));   // ff

Console.WriteLine($"0x{ptr.ToString("x")}"); // 0xff
Console.WriteLine($"0x{ptr:x}"); //0x255
Run Code Online (Sandbox Code Playgroud)

为什么最后两行输出不同的结果?我错过了什么吗?

用 DotnetFiddle 试试

作为旁注,这里是dotnet core 中 IntPtr ToString()的源代码

public unsafe  String ToString(String format) 
    {
        #if WIN32
            return ((int)m_value).ToString(format, CultureInfo.InvariantCulture);
        #else
            return ((long)m_value).ToString(format, CultureInfo.InvariantCulture);
        #endif
    }
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 6

您的示例代码:

Console.WriteLine($"0x{ptr:x}");
Run Code Online (Sandbox Code Playgroud)

相当于它的string.Format兄弟:

Console.WriteLine(string.Format("0x{0:x}", ptr));
Run Code Online (Sandbox Code Playgroud)

应用格式字符串时"x",字符串插值/字符串格式最终会到达以下代码行

IFormattable formattableArg = arg as IFormattable;
Run Code Online (Sandbox Code Playgroud)

不幸的是,虽然IntPtr有一个自定义格式的ToString() 方法,但它没有实现IFormattable,所以它的基本.ToString()方法被调用,格式字符串被丢弃。

请参阅此问题以获取更多信息

正如 vasily.sib 建议的那样,您可以$"0x{(int)ptr:x}"改用。

试试我的例子


归档时间:

查看次数:

116 次

最近记录:

5 年,7 月 前