string.Format将字符串粘贴为不带引号的参数

时间:2018-11-12 14:00:59

标签: c# .net string string-formatting interpolation

我正在格式化字符串:

string.Format(
            "{{\"EventType\":\"{0}\",\"OrganizationId\":\"{1}\",\"Timestamp\":{2},\"ExecutionTime\":{3},\"Success\":{4}}}",
            telemetryEvent.EventType ?? "null", telemetryEvent.OrganizationId ?? "null", telemetryEvent.Timestamp,
            telemetryEvent.ExecutionTime, telemetryEvent.Success);

如果它为null,我需要获取null而不是字符串。

例如““ OrganizationId”:空” 但我却得到了““ OrganizationId”:“ null”“

谢谢

3 个答案:

答案 0 :(得分:1)

我认为最简单的解决方案可能是使用replace

string.Format(
        "{{\"EventType\":\"{0}\",\"OrganizationId\":\"{1}\",\"Timestamp\":{2},\"ExecutionTime\":{3},\"Success\":{4}}}",
        telemetryEvent.EventType ?? "null", telemetryEvent.OrganizationId ?? "null", telemetryEvent.Timestamp,
        telemetryEvent.ExecutionTime, telemetryEvent.Success)
    .Replace("\"null\"", "null");

You can see a live demo on rextester.

答案 1 :(得分:1)

您将获得“ null”,因为字符串模板已经添加了引号:

"{{\"EventType\":\"{0}\"
  ,\"OrganizationId\":\"{1}\",...

因此,无论您在{0}和{1}中输入什么内容,都将其放在双引号中。

为了摆脱它们,请在变量本身周围加上引号。

更新:抱歉,我的先前版本不正确(感谢Zohar指出了此问题)。该方法是有效的,但您需要使用三元表达式而不是空合并运算符:

"{{\"EventType\":{0},\"OrganizationId\":{1},...
  ,telemetryEvent.EventType != null ? "\"" + telemetryEvent.EventType + "\"" : "null"
  ,telemetryEvent.OrganizationId != null ? "\"" + telemetryEvent.OrganizationId + "\"" : "null",...

尽管这样有点“麻烦”,所以可能有更好的方法。

也许您已经知道,但是通过使用字符串插值(参见https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated),这种字符串构建变得更具可读性。

答案 2 :(得分:0)

您在{1}附近有引号,因此引号将始终出现在输出中。 将它们移到参数1的值中。

string.Format(
        "{{\"EventType\":\"{0}\",\"OrganizationId\":{1},\"Timestamp\":{2},\"ExecutionTime\":{3},\"Success\":{4}}}",
        telemetryEvent.EventType ?? "null", 
        telemetryEvent.OrganizationId ?? "null", "\"" + telemetryEvent.Timestamp + "\"",
        telemetryEvent.ExecutionTime, telemetryEvent.Success);
相关问题