Roslyn Scripting APIでは、値をスクリプトに渡して「グローバル」オブジェクトのプロパティとして渡すことができます。Roslyn:(SourceCodeKind.Scriptを使用して)ドキュメントに変数を渡すことが可能です
ワークスペースAPIを使用するときに同様のことを行うことはできますか?
は、ここに私のサンプルコードです:
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
.WithOverflowChecks(true).WithOptimizationLevel(OptimizationLevel.Release)
.WithUsings("System", "System.Collections", "System.Collections.Generic", "System.Dynamic", "System.Linq");
string userCode = "... end user's code goes here...";
using (var workspace = new AdhocWorkspace() { })
{
string projName = "NewProject132";
var projectId = ProjectId.CreateNewId();
var projectInfo = ProjectInfo.Create(
projectId,
VersionStamp.Create(),
projName,
projName,
LanguageNames.CSharp,
isSubmission: true,
compilationOptions: options,
metadataReferences: references,
parseOptions: new CSharpParseOptions(kind: SourceCodeKind.Script, languageVersion: LanguageVersion.Latest));
var project = workspace.AddProject(projectInfo);
var id = DocumentId.CreateNewId(project.Id);
/*
how do I declare variables that are supposed to be visible to the user's code?
*/
var solution = project.Solution.AddDocument(id, project.Name, userCode);
var document = solution.GetDocument(id);
//get syntax and semantic errors
var syntaxTree = document.GetSyntaxTreeAsync().Result;
foreach (var syntaxError in syntaxTree.GetDiagnostics())
{
//...
}
var model = document.GetSemanticModelAsync().Result;
foreach (var syntaxError in model.GetDiagnostics(new TextSpan(0, userCode.Length)))
{
//...
}
var completionService = CompletionService.GetService(document);
var completions = completionService.GetCompletionsAsync(document, userCode.Length - 1).Result;
}
文書は、ユーザースクリプトが移入されているが、スクリプトは、ホストアプリケーションからいくつかの値にアクセスできるようにする必要があります。
最後の手段として、変数宣言をユーザーのスクリプトの前に追加することができますが、それはちょっと面倒なようです。可能であれば避けたいと思います。
優れた答え。 HostObjectTypeパラメータを指定すると、オートコンプリートで使用可能な変数が作成され、シンボルの適切な検出が有効になり、リフレクションスタッフが実行をソートしました。ありがとう! – anakic