我创建了一个诊断分析器,它报告属性的自定义属性的各种问题。 但是,我无法仅获取属性和/或属性参数的位置(取决于报告的特定诊断)。
由于(当前)需要分析两个属性,我创建了一个辅助方法来确定属性上是否存在该属性:
private static bool HasAttribute(SyntaxNodeAnalysisContext context, string attributeName, out PropertyAttributeData data)
{
var propertyDeclarationSyntax = (PropertyDeclarationSyntax)context.Node;
data = new PropertyAttributeData
{
Type = propertyDeclarationSyntax.Type
};
var propertyAttribute = propertyDeclarationSyntax.AttributeLists.FirstOrDefault()
?.GetAttributes(context.Compilation)
?.FirstOrDefault(attr => attr.AttributeClass?.Name == attributeName);
if (propertyAttribute == null)
{
return false;
}
data.AttributeData = propertyAttribute;
data.ConstructorArg1 = propertyAttribute.ConstructorArguments.FirstOrDefault();
if (propertyAttribute.ConstructorArguments.Length > 1)
{
data.ConstructorArg2 = propertyAttribute.ConstructorArguments.Skip(1).FirstOrDefault();
}
return true;
}
然而,这就是我陷入困境的地方。 我一直使用
context.Node.GetLocation
进行测试,但这强调了属性和特性。 我还尝试过使用 SemanticModel.GetSymbolInfo()
和 SemanticModel.GetDeclaredSymbol()
,以及其他一些东西。 但是,我返回的位置要么是从属性的开头到文件的末尾,要么是报告属性的原始位置(在单独的库中)。
我将如何获取just属性或它的第一个/第二个参数的位置? 任何指导将不胜感激。 短暂性脑缺血发作。
如果您尝试过
(AttributeSyntax)attribute.GetLocation()
,请尝试attribute.Name.GetLocation()
或争论(AttributeArgumentSyntax)argument.Expression.GetLocation()
。很确定这对我有用。