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

问题描述 投票:0回答:1

我已经在.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引发了以下异常:

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

我错过了设置吗?

c# .net-core roslyn
1个回答
0
投票

出现错误的原因是缺少对您刚创建的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);
© www.soinside.com 2019 - 2024. All rights reserved.