如何将{和}放在格式字符串中

时间:2020-03-06 15:00:30  来源:igfitidea点击:

我试图在运行时生成一些代码,在其中放置一些样板内容,并允许用户输入实际的工作代码。我的样板代码看起来像这样:

using System;

public class ClassName
{
    public double TheFunction(double input)
    {
        // user entered code here
    }
}

理想情况下,我想我想使用string.Format插入用户代码并创建唯一的类名称,但是除非格式如下,否则我会在格式字符串上遇到异常:

string formatString = @"
using System;

public class ClassName
{0}
    public double TheFunction(double input)
    {0}
        {2}
    {1}
{1}";

然后我调用string.Format这样的:

string entireClass = string.Format(formatString, "{", "}", userInput);

很好,我可以处理在格式字符串中使用{0}和{1}代替花括号的麻烦,但现在用户输入也不能使用花括号。有没有一种方法可以将格式字符串中的花括号转义,或者将用户代码中的花括号转换为{0}和{1}的好方法?

顺便说一句,我知道这种事情是一个安全问题,等待发生,但这是Windows Forms应用程序,可在未连接到网络的系统上内部使用,因此在这种情况下风险是可以接受的。

解决方案

"{{" 和 "}}"

通过将它们加倍来逃脱它们:

string s = String.Format("{{ hello to all }}");
Console.WriteLine(s); //prints '{ hello to all }'

来自http://msdn.microsoft.com/zh-cn/netframework/aa569608.aspx#Question1

将花括号加倍:string.Format(" {{{0}}}"," Hello,World");将产生{Hello,World}

我想你想要的是这个...

string formatString = @"
using System;

public class ClassName
{{
    public double TheFunction(double input)
    {{
        {0}
    }}
}}";

string entireClass = string.Format(formatString, userInput);

谁可以访问该应用程序时要格外小心。更好的解决方案可能是创建一个仅包含一些有限命令的简单解析器。