我正在尝试编写一个 Roslyn 分析器来检测Enumerable.Count()在数组上调用的用法。这是我的分析器中的相关代码:
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeInvocationExpression, SyntaxKind.InvocationExpression);
}
private static void AnalyzeInvocationExpression(SyntaxNodeAnalysisContext context)
{
var invocation = (InvocationExpressionSyntax)context.Node;
var memberAccess = invocation.Expression as MemberAccessExpressionSyntax;
if (!memberAccess.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
return;
}
Debug.Assert(memberAccess != null);
var ident = memberAccess.Name.Identifier;
// Check whether the method is Count() and there is no parameter list before we try to use the Symbol APIs.
if (ident.ToString() != nameof(Enumerable.Count))
{
return;
}
var arguments = invocation.ArgumentList.Arguments;
if (arguments.Count > 0)
{
return;
}
// Make sure that the subject is an array.
var subject = memberAccess.Expression;
var subjectSymbol = context.SemanticModel.GetSymbolInfo(subject).Symbol;
if (subjectSymbol == null)
{
return;
}
// ???
}
Run Code Online (Sandbox Code Playgroud)
我被困在试图确定Count()被调用的对象是否是一个数组。我稍微扫描了 API,我看到有一个ILocalSymbol带有Type属性的属性,还有一个IFieldSymbol带有Type属性的属性,这两种属性都可能为您提供对象的类型。但是,我不知道我正在分析的对象是否是方法调用/等的本地/字段/结果,所以我希望IFieldSymbol并且ILocalSymbol例如共享一些通用的基本接口,例如IVariableSymbol,为您提供Type无需知道变量可能来自的所有可能位置。但是,似乎两个接口都是直接从ISymbol.
最好的解决方案是做这样的事情吗?
internal static class SymbolUtilities
{
public static ITypeSymbol GetType(ISymbol symbol)
{
if (symbol is IFieldSymbol)
{
return ((IFieldSymbol)symbol).Type;
}
if (symbol is ILocalSymbol)
{
return ((ILocalSymbol)symbol).Type;
}
...
}
}
Run Code Online (Sandbox Code Playgroud)
You can get the information about the type, using the method GetTypeInfo of the SemanticModel class:
ITypeSymbol subjectType = context.SemanticModel.GetTypeInfo(subject).Type;
Run Code Online (Sandbox Code Playgroud)
You will find more details about it in the article
"Introduction to Roslyn and its use in program development"