c# - 关于带参数的 Debug.Writeline() 的简单 C# 问题

标签 c#

在调试我的应用程序时,我遇到了一个让我感到困惑的行为。我有以下内容

foreach (var customer in _dbContext.Customer)
{
  Debug.WriteLine("Customer Name: {0}", customer.Name);  // The output was not what I expected.
...
}

实际输出

彼得:客户姓名:{0}

但是,如果我将语句重写为这个。

foreach (var customer in _dbContext.Customer)
{
  Debug.WriteLine("Customer Name: " + customer.Name);  
...
}

实际输出

客户姓名:彼得

我将以下代码添加到同一个文件中,看看为什么我的原始代码不起作用。

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}

非常感谢

最佳答案

问题的发生是因为方法的重载。当您将 string 作为第二个参数传递时,它映射到以下方法:

enter image description here

如您所见,此重载并不像您希望在字符串中替换它们时那样期望“参数”,而是等待调试信息的“类别”。

由于以下重载,将字符串转换为对象的代码有效:

enter image description here

如您所见,当您将字符串转换为“object”时,它映射到 WriteLine 方法的另一个重载,该方法实际上期望将值格式化为字符串。我相信这回答了您关于为什么它在转换为对象时有效的疑问。

关于c# - 关于带参数的 Debug.Writeline() 的简单 C# 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54913686/

相关文章:

c# - 结果 : 0x80040154 (REGDB_E_CLASSNOTREG))

c# - 如何查看 Entity Framework 的未决更改?

C# : Change String Encoding?

c# - 强密码正则表达式

c# - 当我的复合根引用数据层时,我的 DI 架构是否正确?

c# - 从枚举中获取 DescriptionAttribute

c# - 我可以使用 Linq 从 IEnumerables 构建元组吗?

c# - ASP.NET MVC CSRF 防伪 token 会过期吗?

c# - 将自定义对象序列化为 XML

c# - 点之间的数字子串