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

后端 未结 4 772
后悔当初
后悔当初 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:01

    Not sure if this is the simplest way, but by referencing the Microsoft.JScript namespace you can reparse it with the javascript eval function.

    Here's a test for the code at the bottom

    var evalToString = Evaluator.MyStr("test \\r\\n test");
    

    This will turn the \r into a carriage return.

    And the implementation

    public class Evaluator
    {
        public static object MyStr(string statement)
        {
            return _evaluatorType.InvokeMember(
                        "MyStr",
                        BindingFlags.InvokeMethod,
                        null,
                        _evaluator,
                        new object[] { statement }
                     );
        }
    
        static Evaluator()
        {
            ICodeCompiler compiler;
            compiler = new JScriptCodeProvider().CreateCompiler();
    
            CompilerParameters parameters;
            parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;
    
            CompilerResults results;
            results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);
    
            Assembly assembly = results.CompiledAssembly;
            _evaluatorType = assembly.GetType("Evaluator.Evaluator");
    
            _evaluator = Activator.CreateInstance(_evaluatorType);
        }
    
        private static object _evaluator = null;
        private static Type _evaluatorType = null;
        private static readonly string _jscriptSource =
    
            @"package Evaluator
            {
               class Evaluator
               {
                  public function MyStr(expr : String) : String 
                  { 
                     var x;
                     eval(""x='""+expr+""';"");
                     return x;
                  }
               }
            }";
    }
    

提交回复
热议问题