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

string.Format paste string as parameter without quotes

我正在格式化一个字符串:

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

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

例如“"OrganizationId":空” 但我得到的是“"OrganizationId":"null"”

谢谢

我认为最简单的解决方案可能是使用 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.

您得到 "null",因为字符串模板已经添加了引号:

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

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

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

更新: 抱歉,我以前的版本不正确(感谢 Zohar 发现了这一点)。该方法有效,但您需要使用三元表达式而不是空合并运算符:

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

它变得 "a bit" 像这样很麻烦,所以可能有更好的方法。

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

您在 {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);