我试图检测将模型作为参数传递给MVC应用程序的控制器中的函数。我已经为Roslyn诊断分析器编写了代码。代码的逻辑很好,因为按预期命中了断点。但是就警告而言的诊断结果并未反映在已打开的Visual Studio实例中。

这是我的诊断分析器的代码片段:

public override void Initialize(AnalysisContext context)
{
    // TODO: Consider registering other actions that act on syntax instead of or in addition to symbols
    context.RegisterSyntaxNodeAction(AnalyzeSymbol, SyntaxKind.MethodDeclaration);
}

private async static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
{
    var method = (MethodDeclarationSyntax)context.Node;

    ParameterListSyntax ParamList = method.ParameterList;
    int flag = 0;
    string ParamName = null;

    foreach (ParameterSyntax Param in ParamList.Parameters)
    {
        if (Param.Type.ToString().Contains("Model"))
        {
            ParamName = Param.Type.ToString();
            flag = 1;
            break;
        }
    }

    if (flag == 0)
        return;

    string solutionPath = @"C:\Users\Administrator\Documents\Visual Studio 2015\Projects\WebApplication6\WebApplication6.sln";
    var workspace = MSBuildWorkspace.Create();
    var solution = await workspace.OpenSolutionAsync(solutionPath);

    foreach (var project in solution.Projects)
    {
        foreach (var document in project.Documents)
        {
            CancellationToken source = default(CancellationToken);

            SyntaxNode root = await document.GetSyntaxRootAsync(source);

            var classDeclarations = root.DescendantNodes().Where(n => n.IsKind(SyntaxKind.ClassDeclaration));
            flag = 0;

            foreach (ClassDeclarationSyntax cls in classDeclarations)
            {
                if (cls.Identifier.Text.ToString() == ParamName)
                {

                        var diagnostic = Diagnostic.Create(Rule, method.GetLocation());
                        context.ReportDiagnostic(diagnostic);
                }
            }
        }
    }
}

最佳答案

看来您对类的搜索不正确。您应该根据上下文进行操作,而不应该打开新的解决方案。上下文包含有关打开的解决方案的所有必要信息。

关于c# - Roslyn诊断分析器的诊断未反射(reflect)在Visual Studio实例中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31097663/

10-13 06:04