是的,我认为 Roslyn 及其代码问题正是解决此问题的正确工具。使用它们,您可以在键入时分析代码并创建在 Visual Studio 中显示为其他错误的错误(或警告)。
我试图创建这样的代码问题:
[ExportSyntaxNodeCodeIssueProvider("PropertyExpressionCodeIssue", LanguageNames.CSharp, typeof(InvocationExpressionSyntax))]
class PropertyExpressionCodeIssueProvider : ICodeIssueProvider
{
[ImportingConstructor]
public PropertyExpressionCodeIssueProvider()
{}
public IEnumerable<CodeIssue> GetIssues(IDocument document, CommonSyntaxNode node, CancellationToken cancellationToken)
{
var invocation = (InvocationExpressionSyntax)node;
var semanticModel = document.GetSemanticModel(cancellationToken);
var semanticInfo = semanticModel.GetSemanticInfo(invocation, cancellationToken);
var methodSymbol = (MethodSymbol)semanticInfo.Symbol;
if (methodSymbol == null)
yield break;
var attributes = methodSymbol.GetAttributes();
if (!attributes.Any(a => a.AttributeClass.Name == "PropertyExpressionAttribute"))
yield break;
var arguments = invocation.ArgumentList.Arguments;
foreach (var argument in arguments)
{
var lambdaExpression = argument.Expression as SimpleLambdaExpressionSyntax;
if (lambdaExpression == null)
continue;
var parameter = lambdaExpression.Parameter;
var memberAccess = lambdaExpression.Body as MemberAccessExpressionSyntax;
if (memberAccess != null)
{
var objectIdentifierSyntax = memberAccess.Expression as IdentifierNameSyntax;
if (objectIdentifierSyntax != null
&& objectIdentifierSyntax.PlainName == parameter.Identifier.ValueText
&& semanticModel.GetSemanticInfo(memberAccess, cancellationToken).Symbol is PropertySymbol)
continue;
}
yield return
new CodeIssue(
CodeIssue.Severity.Error, argument.Span,
string.Format("Has to be simple property access of '{0}'", parameter.Identifier.ValueText));
}
}
#region Unimplemented ICodeIssueProvider members
public IEnumerable<CodeIssue> GetIssues(IDocument document, CommonSyntaxToken token, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public IEnumerable<CodeIssue> GetIssues(IDocument document, CommonSyntaxTrivia trivia, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
#endregion
}
用法是这样的:
[AttributeUsage(AttributeTargets.Method)]
class PropertyExpressionAttribute : Attribute
{ }
…
[PropertyExpression]
static void Foo<T>(Expression<Func<SomeType, T>> expr)
{ }
…
Foo(x => x.P); // OK
Foo(x => x.M()); // error
Foo(x => 42); // error
上面的代码有几个问题:
- 它完全未优化。
- 它可能需要更多的错误检查。
- 这没用。至少在当前的 CTP 中。
semanticModel.GetSemanticInfo(memberAccess, cancellationToken).Symbol
接近结尾的表达式总是返回null
。这是因为表达式树的语义是当前未实现的特性之一。