Can I expand a string that contains C# literal expressions at runtime

后端 未结 4 776
后悔当初
后悔当初 2020-11-29 11:36

If I have a string that contains a c# string literal expression can I \"expand\" it at runtime

    public void TestEvaluateString()
    {
        string Dumm         


        
4条回答
  •  野性不改
    2020-11-29 12:18

    Similar to Mikael answer but using the 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;
        }
    

    You might be better off using a dictionary of wildcards and just replacing them in the string.

提交回复
热议问题