gpt4 book ai didi

c# - Roslyn CompletionService 不返回静态扩展方法

转载 作者:行者123 更新时间:2023-12-03 23:49:34 32 4
gpt4 key购买 nike

如果'使用 System.Linq;'存在并且 System.Linq 是引用的程序集之一,我希望 int[] 数组上的 Completions 返回 LINQ 扩展方法,例如Select<>(...), Where<>(...) 等。事实上,我只获取 int[] 类型的公共(public)方法和属性。
这是完整的代码:

static void Main(string[] args)
{
string code = @"using System;
using System.Linq;

namespace RoslynCompletionTests
{
public static class MyTestClass1
{
public static void Print()
{
int[] array = {1,2,3,4,5,6};

var result = array.Select(i => new { I = i }).Select(v => v.I);
}
}
}";
var host = MefHostServices.Create(MefHostServices.DefaultAssemblies);

Type[] types =
{
typeof(object),
typeof(Enumerable),
typeof(IEnumerable),
typeof(Console),
typeof(Assembly),
typeof(List<>),
typeof(Type)
};

ImmutableArray<string> imports = types.Select(x => x.Namespace).Distinct().ToImmutableArray();

ImmutableArray<MetadataReference> references =
types.Select(t => MetadataReference.CreateFromFile(t.Assembly.Location) as MetadataReference)
.ToImmutableArray();

AdhocWorkspace workspace = new AdhocWorkspace(host, "Custom");

string name = "MyTestProj";

ProjectId id = ProjectId.CreateNewId(name);

ParseOptions parseOptions = new CSharpParseOptions();

CompilationOptions compilationOptions =
new CSharpCompilationOptions
(
OutputKind.DynamicallyLinkedLibrary,
usings: imports,
allowUnsafe: true);

ProjectInfo projInfo =
ProjectInfo.Create
(
id,
VersionStamp.Create(),
name,
name,
LanguageNames.CSharp,
parseOptions: parseOptions,
compilationOptions: compilationOptions,
metadataReferences: references);

Project proj = workspace.AddProject(projInfo);

SourceText text = SourceText.From(code);

Document doc = proj.AddDocument("MyDoc.cs", text);

SemanticModel semanticModel = doc.GetSemanticModelAsync().Result;

CompletionService completionService = CompletionService.GetService(doc);

string strToFind = "array.";
int idx = text.ToString().IndexOf(strToFind) + strToFind.Length;

var results = completionService.GetCompletionsAsync(doc, idx).Result;
}

难道我做错了什么?

最佳答案

事实证明,我必须添加对构成 MetadataReferences 的某些程序集的引用:

var assemblies = types.Select(t => t.Assembly).Concat(new[]
{
Assembly.Load("System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly,
});

之后一切都开始工作了。

关于c# - Roslyn CompletionService 不返回静态扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59791893/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com