在调试我的应用程序时,我遇到了一个让我感到困惑的行为。我有以下几点
foreach (var customer in _dbContext.Customer)
{
Debug.WriteLine("Customer Name: {0}", customer.Name); // The output was not what I expected.
...
}
实际产出
Peter:客户名称:{0}
但是,如果我将语句重写为。
foreach (var customer in _dbContext.Customer)
{
Debug.WriteLine("Customer Name: " + customer.Name);
...
}
实际产出
客户名称: Peter
我将以下代码添加到相同的文件中,以了解我的原始代码无法工作的原因。
string first = "Peter";
string last = "Piper";
string what = "pick";
Debug.WriteLine("1 {0} 2 {1}, 3 {0} 4 {1}, 5 {2}.", first, last, what);
实际产出
1彼得2吹笛手,3彼得4吹笛手,5选择。
我不确定为什么Debug.WriteLine("Customer Name: {0}", customer.Name);
会输出这个CusPeter:Customer Name: {0}
非常感谢
发布于 2019-02-28 04:42:07
这个问题是由于方法的重载而发生的。当您将string
作为第二个参数传递时,它将映射到以下方法:
正如您所看到的,这个重载并不需要“参数”,当您想要在字符串中替换它们时,它只是在等待“类别”的调试信息。
将字符串转换为object的代码由于以下重载而起作用:
正如您所看到的,当您将字符串转换为"object“时,它会映射到WriteLine
方法的另一个重载,该重载实际上是希望将值格式化为字符串。我相信这回答了你的疑问,为什么它在转换为object时会起作用。
发布于 2019-02-28 04:42:34
一种可行的替代方案是使用$ string interpolation
产生以下结果
Debug.Writline($"CustomerName {customer.Name});
我无意中在评论中回答了这个问题,但发现真正的原因是here,我们命中了错误的重载,而不是插值。
https://stackoverflow.com/questions/54913686
复制相似问题