简体   繁体   中英

Roslyn: Declare variables and then list them

What I'm looking for seems to be overlapping the scripting and compiling features of Roslyn compiler as such I am confused as to which one I should be using.

I'd like to declare/define variables (and evaluate their values) as I go along and at some point list then perhaps by name/type. Do I need CodeAnalysis package or Compiler for that? and how?

Example:

// I'd like to add the following to my scripting or compilation engine:
int a = 1 + 2;
string b = "some " + a;
// and then get a listing of their names, types, and values:
foreach(var myvar in script.ListVariables())
  Console.WriteLine(myvar.Name + " " + myvar.Type + " " + myvar.Value.ToString());

Actually I found the answer and it was quite simple. All I needed was the Scripting engine. To get variables I did something like the last line in the following snippet:

        var script = CSharpScript.Create("");
        script = script.ContinueWith("int a = 10;");
        script = script.ContinueWith("int b = 20;");

        var vars = script.RunAsync().Result.Variables;
        foreach(var v in vars)
        {
            Console.WriteLine($"{v.Name}, {v.Type}, {v.Value.ToString()}");
        }

The result would be something like:

a, System.Int32, 10
b, System.Int32, 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM