C#:从字符串和引用局部变量执行代码
C#: Execute Code from String and Reference Local Variable
我正在开发 C# 应用程序,我希望能够从字符串中执行代码,其中该字符串在字符串外部的范围内包含一个变量。例如:
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");
}
}
显然,我遇到的主要困难是从 userProvidedExpression 中获取 "curNumber",使其被识别为来自 foreach 循环的相同 curNumber。有什么简单的方法可以做到这一点?
As the documentation says,你需要添加一个全局变量,像这样:
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();
}
我正在开发 C# 应用程序,我希望能够从字符串中执行代码,其中该字符串在字符串外部的范围内包含一个变量。例如:
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");
}
}
显然,我遇到的主要困难是从 userProvidedExpression 中获取 "curNumber",使其被识别为来自 foreach 循环的相同 curNumber。有什么简单的方法可以做到这一点?
As the documentation says,你需要添加一个全局变量,像这样:
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();
}