加载正在编写独立代码分析器的解决方案

Load the solution in which the Stand-Alone code Analyser is being written

我正在尝试编写一个分析器来获取有关使用 roslyn 语法树的某些方法的信息。问题是:我正在编写的分析器需要与我要分析的解决方案位于同一解决方案中。 所以,这是我的代码:

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

public static class Main
{

    public static Solution solution { get; set; } = null;

    public static string GetMethodInfo(string methodToFind)
    {

        Task<Solution> GetSolutionTask = null;
        string namespaceToFind, classToFind, methodToFind, invocationToFind;
        if (solution == null)
        {
            var workspace = Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace.Create();
            GetSolutionTask = workspace.OpenSolutionAsync(Config.SolutionPath);
        }
        if (GetSolutionTask != null) solution = GetSolutionTask.Result;
        foreach (Project proj in solution.Projects)
        {
            Compilation compilation = proj.GetCompilationAsync().Result;
            foreach (var tree in compilation.SyntaxTrees)
            {
                findMethodAndProcessIt()...
            }
        }
        return String.Empty;
    }
}

我遇到的问题是没有编译有任何语法树。我通过打开其他解决方案尝试了相同的代码并且它有效。很明显,这里的问题是试图打开 visual studio 正在使用的解决方案。 我已经尝试 运行 此代码 visual studio 关闭,仅 运行 连接 .exe ,但问题仍然存在。 您知道如何解决这个问题吗?

您正在使用 MSBuildWorkspace 打开解决方案。通常,当使用 MSBuildWorkspace 导致项目未正确加载、没有源文件等时,在 msbuild 处理期间出现故障。当您的应用程序在其 app.config 文件中没有与 msbuild 使用的(在 msbuild.exe.config 中)相同的绑定重定向时,通常会发生这种情况,这会导致某些自定义 tasks/extensions 由于版本控制不匹配而无法加载.

您需要将 部分复制到您的 app.config。