首页 > 解决方案 > 为 roslyn 脚本项目设置基类

问题描述

所以我有一个编译器类,用于运行用户代码。现在我的问题是我的文档是脚本文档,我不知道如何为这些文档设置基类。我一直在寻找 hostObjectType 但我看到 isSubmission 必须是真的,但我不能这样做,因为我的其余代码会中断。

初始化编译器的代码:

public static async Task Init(Type host, params Assembly[] assemblies)
{
  await Task.Run(() =>
  {
    IsInitialized = true;
    workspace = new AdhocWorkspace();

    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true, usings: new string[] { "CCreative" }, platform: Platform.X64)
      .WithMetadataImportOptions(MetadataImportOptions.All);

    var scriptProjectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Script", "Script", LanguageNames.CSharp, isSubmission: false, hostObjectType: host)
                                       .WithMetadataReferences(assemblies.Select(x => MetadataReference.CreateFromFile(x.Location, default, x.Location.Contains("CCreative") ? new CCreativeDocumentationProvider() : null)))
                                       .WithCompilationOptions(compilationOptions);

    project = workspace.AddProject(scriptProjectInfo);
    workspace.TryApplyChanges(project.Solution.WithOptions(GetOptions(workspace)));
  });
}

所以我的目标是将所有脚本文档的基类设置为主机参数。

创建文档的代码:

public static DocumentId AddDocument(string text)
{
  var scriptDocumentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id),
                                               "Script",
                                               sourceCodeKind: SourceCodeKind.Script,
                                               loader: TextLoader.From(TextAndVersion.Create(SourceText.From(text), VersionStamp.Create())));

  var scriptDocument = workspace.AddDocument(scriptDocumentInfo);

  project = scriptDocument.Project;
  workspace.TryApplyChanges(project.Solution);

  return scriptDocument.Id;
}

欢迎任何帮助:)

标签: c#scriptingroslyn

解决方案


推荐阅读