当前上下文中不存在名称'xxx'(是否缺少对程序集的引用)



我已经安装了Microsoft.CodeAnalysis.CSharp&.Net Core 2.2控制台应用程序中的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抛出以下异常:

名称"Age"在当前上下文中不存在(是否缺少对程序集"DynamicAssembly,Version=0.0.0.0,Culture=neutral,PublicKeyToken=null"的引用?(">

是否有我错过的设置?

出现错误的原因是没有引用刚刚创建的DynamicAssembly。要解决此问题,可以将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);

相关内容

最新更新