我可以在运行时扩展包含C#文字表达式的字符串

And*_*ris 8 c#

如果我有一个包含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)

你可能最好使用通配符字典,只需在字符串中替换它们.

  • 我无法相信这样做的唯一方法是在用户的终端系统上编译DLL文件(仅将其保留在临时目录中).如果这段代码被多次调用,那就相当慢了.答案为+1,因为它有效,但我真的希望看到更好的解决方案. (2认同)

Lin*_*gxi 6

Regex.Unescape将是我选择的方法。