格式化字符串-输入的字符串格式不正确

时间:2020-08-15 21:15:29

标签: c# string.format

我想要一个函数来接收一个字符串并将其格式化为C#中以下格式的另一个字符串:(测试是一个输入变量)

output:
@"{MyKey=testing}"

我的简单程序如下:

class Program
{
    static void Main(string[] args)
    {
        string s = test("testing");
    }
    private static string test(string myKey)
    {
        string s = string.Format("@{\"MyKey={0}\"}", myKey);
        return s;
    }
}

没有语法错误,但出现此运行时错误:

enter image description here

我知道字符串包含特殊字符,但是我想知道是否可以使用string.Format创建我想要的输出?我应该如何正确格式化字符串?

1 个答案:

答案 0 :(得分:4)

您需要使用双花括号来转义那些应该属于字符串的花括号。查看更多here

class Program
{
    static void Main(string[] args)
    {
        string s = test("testing");
        s.Dump();
    }
    private static string test(string myKey)
    {
        string s = string.Format("@{{\"MyKey={0}\"}}", myKey);
        return s;
    }
}

您还可以像这样使用字符串插值:

string s = $"@{{\"MyKey={myKey}\"}}";