【问题标题】:Email subject = string subject = "test {0}", test2; Outputs:"test {0}"电子邮件主题 = 字符串主题 = "test {0}", test2;输出:“测试 {0}”
【发布时间】:2018-03-20 21:31:51
【问题描述】:

我正在创建一个程序,该程序会发送一封电子邮件,其中包含程序事先从用户那里收集的一些数据。

目前,我的问题是当我使用时:

string subject = "test {0}", test2;

我收到的电子邮件是这样的输出:

测试{0}

而不是预期的输出:

“测试测试2”。

我有什么遗漏吗?

我刚刚通过删除文本并仅将变量用作主题来测试其他内容,效果很好。但是为什么 text/string + 变量不起作用?

Vs 表示我要添加的变量 test2 已经定义。

完整代码:

string test2 = "test";
string subject = "test {0}", test2;
string body = "test1";

【问题讨论】:

  • 您需要说明您使用的是什么编程语言,并显示minimal reproducible example
  • 语言添加,c#,我忘记了,因为我改变了我的标题,很抱歉给您带来不便。
  • 是的,谢谢

标签: c# string email variables subject


【解决方案1】:

这是因为您需要将格式化字符串包装在 String.Format() 或 Console.WriteLine() 中;

应该是

string test2 = "test";
string subject = String.Format("test {0}", test2);
string body = "test1";

没有 String.Format C# 只会认为您定义了 2 个单独的字符串变量。它创建了一个名为 subject 的变量,它等于“test {0}”和另一个名为 test2 的变量,您已经在之前的行中定义了它,这就是它抱怨的原因。 它认为你想说

string test2 = "test";
string subject = "test {0}";
string test2;
string body = "test1";

阅读复合格式的文档。 https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting

【讨论】:

  • 好的,谢谢,成功了。太棒了,ty
猜你喜欢
  • 2019-03-30
  • 2021-04-20
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多