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

我正在尝试在运行时生成一些代码,我在其中添加了一些样板代码,用户可以输入实际的工作代码。 我的样板代码看起来像这样:

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

理想情况下,我想我想使用string.Format插入用户代码并创建一个唯一的类名,但我得到格式字符串的exception,除非它看起来像这样:

 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/en-us/netframework/aa569608.aspx#Question1

“{{”和“}}”

我想你想要的是……

 string formatString = @" using System; public class ClassName {{ public double TheFunction(double input) {{ {0} }} }}"; string entireClass = string.Format(formatString, userInput); 

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

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