我一直在使用 RoslynCodeEditor 控件并试图找到一种方法将我的全局对象传递给 RoslynCodeEditor 并在我的脚本中使用智能感知。

有谁知道在使用 RoslynCodeEditor 控件编辑我的脚本时如何授予对上下文对象属性或方法的访问权限?

MyContext context = new MyContext();
context.Data = data;
ScriptOptions scriptOptions = ScriptOptions.Default;
scriptOptions = scriptOptions.WithReferences(ReferencesAndImports.References);
scriptOptions = scriptOptions.WithImports(ReferencesAndImports.Imports);
var scriptState = await CSharpScript.EvaluateAsync<string>("int i = 0;", scriptOptions, context, typeof(MyContext));

最佳答案

您需要将 globals 类型添加到设计时编译中。为此,您需要一个自定义的 RoslynHost(在 2.4 及更高版本中受支持):

public class CustomRoslynHost : RoslynHost
{
    protected override Project CreateProject(Solution solution, DocumentCreationArgs args, CompilationOptions compilationOptions, Project previousProject = null)
    {
        var name = args.Name ?? "Program";
        var id = ProjectId.CreateNewId(name);

        var parseOptions = new CSharpParseOptions(kind: SourceCodeKind.Script, languageVersion: LanguageVersion.Latest);

        compilationOptions = compilationOptions.WithScriptClassName(name);

        solution = solution.AddProject(ProjectInfo.Create(
            id,
            VersionStamp.Create(),
            name,
            name,
            LanguageNames.CSharp,
            isSubmission: true,
            parseOptions: parseOptions,
            hostObjectType: typeof(MyContext),
            compilationOptions: compilationOptions,
            metadataReferences: previousProject != null ? ImmutableArray<MetadataReference>.Empty : DefaultReferences,
            projectReferences: previousProject != null ? new[] { new ProjectReference(previousProject.Id) } : null));

        var project = solution.GetProject(id);

        return project;
    }
}

然后添加对类型所在程序集的引用。例如:
new CutomRoslynHost(
    references: RoslynHostReferences.Default.With(
        typeNamespaceImports: new[] { typeof(MyContext) }),
    additionalAssemblies: ...);

关于c# - 是否可以在 RoslynPad RoslynCodeEditor 控件中为 globalsType 的对象全局包含智能感知?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47293326/

10-10 01:22