Roslyn 分析器标记 return 类型 属性

Roslyn Analyzer to mark return type of property

我正在为 Roslyn 编写分析器,需要标记 属性 的 return 类型。我用它来标记 属性 声明本身。我查看了调试器,但找不到针对 return 类型标记的位置。

示例:

// important code for analzyer

public override void Initialize(AnalysisContext context)
{
    context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.MethodDeclaration, SyntaxKind.PropertyDeclaration);
}

private static void AnalyzeSyntax(SyntaxNodeAnalysisContext context)
{
    var propertySymbol = context.ContainingSymbol as IPropertySymbol;
    var propertyType = propertySymbol.Type;
    if (propertyType.Name != "Class1") return;

    var diagnostic = Diagnostic.Create(Rule, propertySymbol.Locations[0], propertyType.Name);
    context.ReportDiagnostic(diagnostic);
    break;
}

// example where it should be working

public class Usage
{
    public Class1 Test { get; set; }
}

它目前在 Usage.Test 属性 名称下放置绿色波浪形,但我希望它在 return 类型下 属性。

context.ContainingSymbol有一个Locations属性,但它只指定了一个位置,而且它只指向Testcontext.Node 指定了一些覆盖整个 属性 的其他范围,但它不是完整的 Location 对象,所以我不能使用它们。

编辑 1

显然,我在 VS 2017 的 .Net Standard 中执行此操作很重要。.Net 4.5 分析器可以通过 MSBuildWorkspaceSymbolFinder 类 访问用法,但是 .Net Standard 由于某种原因没有 MSBuildWorkspace 所以我无法将当前解决方案传递给 SymbolFinder.FindReferencesAsync().

The context.Node specifies a few other spans that cover the entire property, but it's not a full Location object, so I can't use them.

答案在于从 TextSpan 创建 Location。为此,您可以使用 Location.Create() 接受语法树和跨度。这些都可以通过 context.Node 属性.

var propertyTypeIdentifier = ((PropertyDeclarationSyntax) context.Node).Type;

name = propertyType.Name;
location = Location.Create(propertyTypeIdentifier.SyntaxTree, propertyTypeIdentifier.Span);