本文介绍了你怎么把{和}在格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想产生一些code运行时,我把一些样板化的东西,用户被允许进入实际工作code。我的样板code看起来是这样的:

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
    }
}

在理想情况下,我想,我想用的String.Format插入用户code和创造一个独特的类名,但除非它看起来是这样的,我得到的格式字符串异常:

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}";

然后,我打电话的String.Format是这样的:

Then I call string.Format like this:

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

这是好的,我可以使用的丑陋处理{0}和{1}在格式字符串代替我的花括号只是现在我的用户输入无法使用大括号无论是。有没有一种方法来逃避花括号在我的格式字符串,或打开大括号在用户code变成一个很好的方法{0}的和{1}的?

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?

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

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.

推荐答案

通过加倍起来躲避他们的:

Escape them by doubling them up:

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

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

这篇关于你怎么把{和}在格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 07:56