C# 如何将{和}放入格式字符串中
我试图在运行时生成一些代码,在其中我放入一些锅炉板材料,用户可以输入实际的工作代码。我的锅炉铭牌代码如下所示:C# 如何将{和}放入格式字符串中,c#,.net,string,formatting,C#,.net,String,Formatting,我试图在运行时生成一些代码,在其中我放入一些锅炉板材料,用户可以输入实际的工作代码。我的锅炉铭牌代码如下所示: using System; public class ClassName { public double TheFunction(double input) { // user entered code here } } string formatString = @" using System; public class ClassNam
using System;
public class ClassName
{
public double TheFunction(double input)
{
// user entered code here
}
}
string formatString = @"
using System;
public class ClassName
{0}
public double TheFunction(double input)
{0}
{2}
{1}
{1}";
string entireClass = string.Format(formatString, "{", "}", userInput);
理想情况下,我想使用string.Format插入用户代码并创建一个唯一的类名,但我在格式字符串上遇到一个异常,除非它看起来像这样:
using System;
public class ClassName
{
public double TheFunction(double input)
{
// user entered code here
}
}
string formatString = @"
using System;
public class ClassName
{0}
public double TheFunction(double input)
{0}
{2}
{1}
{1}";
string entireClass = string.Format(formatString, "{", "}", userInput);
然后我调用string.Format,如下所示:
using System;
public class ClassName
{
public double TheFunction(double input)
{
// user entered code here
}
}
string formatString = @"
using System;
public class ClassName
{0}
public double TheFunction(double input)
{0}
{2}
{1}
{1}";
string entireClass = string.Format(formatString, "{", "}", userInput);
这很好,我可以处理在格式字符串中使用{0}和{1}代替花括号的丑陋问题,但现在我的用户输入也不能使用花括号。是否有一种方法可以转义格式字符串中的大括号,或者有一种好方法可以将用户代码中的大括号转换为{0}和{1}
顺便说一句,我知道这类事情是一个等待发生的安全问题,但这是一个Windows窗体应用程序,供未连接到网络的系统内部使用,因此在这种情况下风险是可以接受的。“{{”和“}}}”通过将它们加倍来避免它们:
string s = String.Format("{{ hello to all }}");
Console.WriteLine(s); //prints '{ hello to all }'
从将大括号加倍:
string.Format(“{{{0}}}”,“你好,世界”)
会产生{你好,世界}
我想你想要的是这个
string formatString = @"
using System;
public class ClassName
{{
public double TheFunction(double input)
{{
{0}
}}
}}";
string entireClass = string.Format(formatString, userInput);
对于谁有权访问该应用程序,要格外小心。更好的解决方案可能是创建一个简单的解析器,该解析器只需要几个有限的命令。这是一个安全问题,因为用户可能执行的代码可以是任何东西,而不是因为它连接到了“网络”。事实上不,仅仅因为代码可以是任何东西,用户就不能做以前做不到的事情。该应用程序与用户在相同的环境中运行,只有能够访问它运行的机器的人才能引入代码。是的,只有5到6个人有理由使用该应用程序,所以就像我说的,风险是可以接受的。