声明包含特殊字符的常量

本文关键字:常量 特殊字符 包含 声明 | 更新日期: 2023-09-27 18:34:02

我有一个包含特殊字符{,[,..的字符串,如下所示:

"[{"name":"print","next":"null","proc":"printproc","func":"null"}]"

要将常量字符串分配给变量,我必须执行以下操作:

string s = "[{'"name'":'"print'",'"next'":'"null'",'"proc'":'"printproc'",'"func'":'"null'"}]";

否则编译器将抛出错误。有没有一种不那么麻烦的方式来声明常量。我尝试在字符串的开头使用 @:

string s = @"[{"name":"print","next":"null","proc":"printproc","func":"null"}]";

但是我也遇到了编译器错误。将常量保存到文本文件中并从中加载将起作用,但这对我来说可能是矫枉过正。有没有人在 C# 中遇到过相同的情况,他们想出了解决方法吗?

声明包含特殊字符的常量

您是否尝试过使用单引号来包装属性名称/值?

例如 string s = @"[{'name':'print','next':'null','proc':'printproc','func':'null'}]"

  1. 你可以放双子:

    string s = @"[{""name"":""print""}]";

  2. 或者,放'

    string s = "[{'"name'":'"print'"}]";

  3. 您可以使用此'而不是"

  4. 以任何方式拆分数据,然后使用它

您可以为所需的每个特殊字符创建一个变量。

为了展示这个概念,我在一个简单的 C# 控制台应用中对此进行了测试。

using System;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string quot = "'"";
            string compound = "Now I can use " + quot + "quotation marks" + quot + " around a variable";
            Console.WriteLine(compound);
        }
    }
}

输出为:

现在我可以在变量周围使用"引号"