我尝试获取代码完成,但是当我尝试通过CompletionService异步获取完成时,我得到了NullReferenceException

这是一段代码:

public async Task<IList<ICompletionData>> GetCompletionData(String code, int offset)
    {
        IList<ICompletionData> completionData = null;

        if (_workspace != null)
        {
            _workspace.Dispose();
        }
        _workspace = new AdhocWorkspace();
        _project = _workspace.AddProject("Test", LanguageNames.CSharp);



        var sourceText = SourceText.From(code);
        var document = _workspace.AddDocument(_project.Id, "Compilation0", sourceText);
        var completionService = CompletionService.GetService(document);
        var charCompletion = GetCompletionTrigger('.');
        var data = await completionService.GetCompletionsAsync(_document, offset,charCompletion,).ConfigureAwait(false);

        if (data == null || data.Items.Any() == false)
            return new List<ICompletionData>();

        completionData = data.Items.Select(item => new RoslynCodeCompletion(_document, item)).ToList<ICompletionData>();

        return completionData;
    }


行错误:

var data = await completionService.GetCompletionsAsync(_document, offset,charCompletion,).ConfigureAwait(false);//NullReferenseException.


脚本代码的代码补全由“。”触发(点)符号:

var str="";
str. // here calls `GetCompletionData`


完整代码段位于pastebin

最佳答案

合并Roslyn PR #14921之后,这变得容易得多。在您需要大量manual MEF configuration之前,但现在应该已经足够安装以下nuget软件包:


微软代码分析
Microsoft.CodeAnalysis.CSharp
Microsoft.CodeAnalysis.Features
Microsoft.CodeAnalysis.CSharp.Features


Roslyn将执行所需的配置。

09-11 18:10