How do you put { and } in a format string [duplica

2020-08-09 06:38发布

I'm trying to generate some code at runtime where I put in some boiler-plate stuff and the user is allowed to enter the actual working code. My boiler-plate code looks something like this:

using System;

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

Ideally, I think I want to use string.Format to insert the user code and create a unique class name, but I get an exception on the format string unless it looks like this:

string formatString = @"
using System;

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

Then I call string.Format like this:

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

This is fine and I can deal with the ugliness of using {0} and {1} in the format string in place of my curly braces except that now my user input cannot use curly braces either. Is there a way to either escape the curly braces in my format string, or a good way to turn the curly braces in the user code into {0}'s and {1}'s?

BTW, I know that this kind of thing is a security problem waiting to happen, but this is a Windows Forms app that's for internal use on systems that are not connected to the net so the risk is acceptable in this situation.

5条回答
萌系小妹纸
2楼-- · 2020-08-09 06:47

Be extra extra cautious in who has access to the application. A better solution might be to create a simple parser that only expects a few, limited, commands.

查看更多
等我变得足够好
3楼-- · 2020-08-09 06:49

Double the braces: string.Format("{{ {0} }}", "Hello, World"); would produce { Hello, World }

查看更多
神经病院院长
4楼-- · 2020-08-09 06:51

"{{" and "}}"

查看更多
一夜七次
5楼-- · 2020-08-09 06:56

What I think you want is this...

string formatString = @"
using System;

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

string entireClass = string.Format(formatString, userInput);
查看更多
虎瘦雄心在
6楼-- · 2020-08-09 07:04

Escape them by doubling them up:

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

From http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1

查看更多
登录 后发表回答