【问题标题】:C# String.Format bug? [closed]C# String.Format 错误? [关闭]
【发布时间】:2021-02-15 16:04:05
【问题描述】:

我无法理解为什么这段代码会产生这样的结果:

$ type t.cs

using System;
using static System.Console;
using static System.Environment;

class P
{
  public static void Main()
  { uint a=1;
    string b="a string";
    string c=String.Format ( $"{0}\t{1}" , a , b) ;
    Out.WriteLine( c );
    Exit(0);
  }
}

$ csc t.cs 
Microsoft (R) Visual C# Compiler version 2.9.0.63208 (958f2354)
Copyright (C) Microsoft Corporation. All rights reserved.
$ .\T.EXE
0       1

我已阅读有关 String.Format 的文档: https://docs.microsoft.com/en-us/dotnet/api/system.string.format?view=net-5.0
但我仍然不知道如何解释上面的代码打印的原因 "01" 而不是 "1a string" 。

谁能给我指点一下?

【问题讨论】:

  • 您将字符串插值与字符串格式混合。只使用其中之一。 string.Format 接收没有任何占位符要替换的字符串,因为插值首先发生
  • 这意味着您需要删除格式化字符串前面的$

标签: c# windows-10 string.format


【解决方案1】:

这个interpolated string字面表达:

$"{0}\t{1}"

将评估为:

"0\t1"

...在传递给 string.Format() 之前 - 因为它没有占位符,所以输入参数被忽略,结果字符串只是 "0\t1"

改为:

string c = String.Format("{0}\t{1}", a, b); // no interpolation of template string

string c = $"{a}\t{b}"; // expand a and b inline using interpolation

【讨论】:

    【解决方案2】:

    因为您使用的是字符串插值 -> $"{}";在这种情况下,{0} 和 {1} 不是占位符,它们是文字。去掉字符串“{0}\t{1}”之前的美元符号,你会得到你所期望的。

    【讨论】:

    • 啊哈!感谢以上所有回答的人!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多