我已经在.Net Core 2.2控制台应用程序中安装了Microsoft.CodeAnalysis.CSharp和Microsoft.CodeAnalysis.CSharp.Scripting(版本3.3.1)程序包,并且我还开发了以下代码:
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
public class MyGlobals
{
public int Age {get; set;} = 21;
}
");
var references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
};
var compilation = CSharpCompilation.Create("DynamicAssembly")
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddSyntaxTrees(syntaxTree)
.AddReferences(references);
Type globalsType = null;
Assembly assembly = null;
using (var memoryStream = new MemoryStream())
{
var compileResult = compilation.Emit(memoryStream);
assembly = Assembly.Load(memoryStream.GetBuffer());
if (compileResult.Success)
{
globalsType = assembly.GetType("MyGlobals");
}
}
var globals = Activator.CreateInstance(globalsType);
var validationResult = CSharpScript.EvaluateAsync<bool>("Age == 21", globals: globals);
创建了globals对象,但不对表达式求值,并且CSharpScript引发以下异常:
The name 'Age' does not exist in the current context (are you missing a reference to assembly 'DynamicAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'?)'
我错过了设置吗?
出现错误的原因是缺少对您刚创建的DinamicAssembly的引用。要解决此问题,您可以将ScriptOptions
传递给CSharpScript.EvaluateAsync<bool>()
呼叫。以下代码对我来说运行良好。
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
public class MyGlobals
{
public int Age {get; set;} = 21;
}
");
var references = new List<MetadataReference>
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
};
var compilation = CSharpCompilation.Create("DynamicAssembly")
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddSyntaxTrees(syntaxTree)
.AddReferences(references);
Type globalsType = null;
Assembly assembly = null;
using (var memoryStream = new MemoryStream())
{
var compileResult = compilation.Emit(memoryStream);
var buffer = memoryStream.GetBuffer();
File.WriteAllBytes("DynamicAssembly.dll", buffer);
assembly = Assembly.LoadFile(Path.GetFullPath("DynamicAssembly.dll"));
if (compileResult.Success)
{
globalsType = assembly.GetType("MyGlobals");
}
}
var globals = Activator.CreateInstance(globalsType);
var options = ScriptOptions.Default.WithReferences("DynamicAssembly.dll");
var validationResult = CSharpScript.EvaluateAsync<bool>(
"Age == 21",
globals: globals,
options: options
);
Console.WriteLine(await validationResult);