dimanche 8 avril 2018

Run .NET code from string and replace variables in runtime

Its a little complicated to explain, I used a CodeProvider in .net in order to parse string to runable code to script my application. here is some code:

        public static Action GetAction(string vbscript)
    {
        var text = string.Format(@" 
                Imports System
                Imports Microsoft.VisualBasic
                Imports CCTView.VbScript
                Class MyConverter
                    Public Shared Sub Convert()
                        {0}                 
                    End Sub
                End Class", vbscript);
        message = new List<string>();
        var prov = new VBCodeProvider();
        var param = new CompilerParameters();
        param.ReferencedAssemblies.Add("System.Core.dll");
        var results = prov.CompileAssemblyFromSource(param, string.Format(text,vbscript));
        var expr = results.CompiledAssembly.GetType("MyConverter")
            .GetMethod("Convert");
        return expr.CreateDelegate(typeof(Action)) as Action;
    }

In code above a statement is given to the function param vbscript then it returns an Action that I can run it when needed.

However, my data is not there as local variables in script namespace. For example I need to Write "ReadDouble("myDouble")" "WriteDouble("MyDouble") to read or write them. (ReadDouble and Writedouble are static methods in the namespace.) Also,I made a custom indexer to warp these operations so it looks like this now: "Doubles["myDouble"]" can both do read and write.

my question is here: is there any way when I provide script statement ,I only need to write myDouble = 123.456 instead of doubles["myDouble"]=123.456 without declare it in the script? using regex to replace words is possible? or I have to write my own parser?

thank you.





Aucun commentaire:

Enregistrer un commentaire