如果我有一个包含ac#string文字表达式的字符串,我可以在运行时"展开"它
public void TestEvaluateString()
{
string Dummy = EvalString( @"Contains \r\n new line");
Debug.Assert(Dummy == "Contains \r\n new line");
}
private string EvalString(string input)
{
return "Contains \r\n new line";
}
Run Code Online (Sandbox Code Playgroud)
就像我可以将C#字符串值转换为转义字符串文字,但反过来?
JDu*_*ley 10
类似于Mikael的答案,但使用CSharpCodeProvider:
public static string ParseString(string txt)
{
var provider = new Microsoft.CSharp.CSharpCodeProvider();
var prms = new System.CodeDom.Compiler.CompilerParameters();
prms.GenerateExecutable = false;
prms.GenerateInMemory = true;
var results = provider.CompileAssemblyFromSource(prms, @"
namespace tmp
{
public class tmpClass
{
public static string GetValue()
{
return " + "\"" + txt + "\"" + @";
}
}
}");
System.Reflection.Assembly ass = results.CompiledAssembly;
var method = ass.GetType("tmp.tmpClass").GetMethod("GetValue");
return method.Invoke(null, null) as string;
}
Run Code Online (Sandbox Code Playgroud)
你可能最好使用通配符字典,只需在字符串中替换它们.