简体   繁体   中英

C#: Execute Code from String and Reference Local Variable

I am working on a C# application, and I would like the ability to execute code from a string, where that string contains a variable in scope outside the string. For example:

using Microsoft.CodeAnalysis.CSharp.Scripting;

///...


List<int> myNumbers = new List<int>();
//do something here to populate myNumbers

//userProvidedExpression will be a string that contains curNumber and represents a statement that would evaluate to a bool
string userProvidedExpression = "curNumber == 4"; 

foreach(int curNumber in myNumbers)
{
    if(   await CSharpScript.EvaluateAsync<bool>(userProvidedExpression) )
    {
        Console.WriteLine("curNumber MATCHES user-provided condition");
    }
    else
    {
        Console.WriteLine("curNumber DOES NOT MATCH user-provided condition");
    }
}

Obviously the key difficulty I am having is getting the "curNumber" from userProvidedExpression to be recognized as the same curNumber from the foreach loop. Is there any straightforward way to accomplish this?

As the documentation says , you need to add a globals, like that:

public class Globals
{
    public int curNumber;
}

async static void Main(string[] args)
{
    List<int> myNumbers = new List<int>();
    myNumbers.Add(4);

    //userProvidedExpression will be a string that contains curNumber and represents a statement that would evaluate to a bool
    string userProvidedExpression = "curNumber == 4";

    foreach (int curNumber in myNumbers)
    {
        var globals = new Globals
        {
            curNumber = curNumber
        };
        if (await CSharpScript.EvaluateAsync<bool>(userProvidedExpression, globals: globals))
        {
            Console.WriteLine("curNumber MATCHES user-provided condition");
        }
        else
        {
            Console.WriteLine("curNumber DOES NOT MATCH user-provided condition");
        }
    }

    Console.ReadLine();
}

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