【发布时间】:2020-01-17 17:07:42
【问题描述】:
如果'使用 System.Linq;'存在并且 System.Linq 是引用的程序集之一,我希望 int[] 数组上的 Completions 返回 LINQ 扩展方法,例如Select(...), Where(...) 等。事实上,我只获取 int[] 类型的公共方法和属性。 完整代码如下:
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;
}
我做错了吗?
【问题讨论】: