Attribute 基本上是一个类型,enum 也是如此。这种模棱两可是标准行为。只需将您的思绪从class Horse 继承Attribute 中解放出来。从这个意义上说,将其视为一种类型。解析类型名称是编译器似乎要做的第一件事。之后检查属性(您尝试用作属性的东西)与Attribute 的兼容性。您指定全名的解决方案是唯一正确的。
更新:
看起来您希望 CS 编译器能够区分属性使用语义以及解析类型名称。可以使用这样的自定义代码分析器手动实现它:
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public partial class AmbiguityAnalysisAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "AA0001";
private static readonly DiagnosticDescriptor Rule =
new DiagnosticDescriptor(id: DiagnosticId,
title: "Specify the attribute.",
messageFormat: "Possible attribute '{0}' is ambiguous between {1}",
category: "Attribute Usage",
defaultSeverity: DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: "Ambiguous attribute.");
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context) =>
context.RegisterSemanticModelAction(SemanticModelAction);
private void SemanticModelAction(SemanticModelAnalysisContext context)
{
var types = GetAllTypes(context.SemanticModel.Compilation).ToArray();
var attributes = GetAllAttribute(context);
var ambiguities = GetAmbiguities(types, attributes);
foreach (var ambiguity in ambiguities)
context.ReportDiagnostic(ambiguity);
}
}
有
public partial class AmbiguityAnalysisAnalyzer
{
private static IEnumerable<INamedTypeSymbol> GetAllTypes(Compilation compilation) =>
GetAllTypes(compilation.GlobalNamespace);
private static IEnumerable<INamedTypeSymbol> GetAllTypes(INamespaceSymbol @namespace)
{
foreach (var type in @namespace.GetTypeMembers())
foreach (var nestedType in GetNestedTypes(type))
yield return nestedType;
foreach (var nestedNamespace in @namespace.GetNamespaceMembers())
foreach (var type in GetAllTypes(nestedNamespace))
yield return type;
}
private static IEnumerable<INamedTypeSymbol> GetNestedTypes(INamedTypeSymbol type)
{
yield return type;
foreach (var nestedType in type.GetTypeMembers()
.SelectMany(nestedType => GetNestedTypes(nestedType)))
yield return nestedType;
}
private static AttributeSyntax[] GetAllAttribute(SemanticModelAnalysisContext context) =>
context
.SemanticModel
.SyntaxTree
.GetRoot()
.DescendantNodes()
.OfType<AttributeSyntax>()
.ToArray();
private static IEnumerable<Diagnostic> GetAmbiguities(INamedTypeSymbol[] types, AttributeSyntax[] attributes)
{
foreach (var attribute in attributes)
{
var usings = GetUsings(attribute.SyntaxTree);
var ambiguities = GetAmbiguities(usings, types, attribute);
if (ambiguities.Length < 2)
continue;
var suggestedAttributes = GetAttributes(ambiguities);
var suggestedNonAttributes = GetNonAttributes(ambiguities);
var parts =
new[]
{
GetPart("attributes", suggestedAttributes),
GetPart("non attributes", suggestedNonAttributes)
}
.Where(part => !part.Equals(string.Empty));
var name = (attribute.Name as IdentifierNameSyntax)?.Identifier.ValueText;
var suggestions =
name == null ?
ImmutableDictionary<string, string>.Empty :
suggestedAttributes.Select(type => GetFullyQualifiedName(type))
.ToImmutableDictionary(type => type, type => name);
var message = string.Join(" and ", parts);
yield return Diagnostic.Create(Rule, attribute.GetLocation(), suggestions, attribute.Name, message);
}
}
}
和其他辅助方法
public partial class AmbiguityAnalysisAnalyzer
{
private static string GetFullyQualifiedName(INamedTypeSymbol type)
{
var @namespace = GetFullName(type.ContainingNamespace, n => !n.IsGlobalNamespace, n => n.ContainingNamespace);
var name = GetFullName(type, t => t != null, t => t.ContainingType);
if (!@namespace.Equals(string.Empty, StringComparison.Ordinal))
return $"{@namespace}.{name}";
return name;
}
private static string[] GetUsings(SyntaxTree syntaxTree) =>
syntaxTree
.GetCompilationUnitRoot()
.Usings.Select(GetUsingString)
.Concat(new[] { string.Empty })
.ToArray();
private static string GetUsingString(UsingDirectiveSyntax @using) =>
GetUsingStringFromName(@using.Name);
private static string GetUsingStringFromName(NameSyntax name)
{
if (name is IdentifierNameSyntax identifierName)
return identifierName.Identifier.ValueText;
if (name is QualifiedNameSyntax qualifiedName)
return $"{GetUsingStringFromName(qualifiedName.Left)}.{GetUsingStringFromName(qualifiedName.Right)}";
throw new ArgumentException($"Argument '{nameof(name)}' was of unexpected type.");
}
private static INamedTypeSymbol[] GetAmbiguities(IEnumerable<string> usings, IEnumerable<INamedTypeSymbol> types, AttributeSyntax attribute) =>
types
.Where(t => attribute.Name is IdentifierNameSyntax name &&
NameMatches(t, name) &&
NamespaceInUsings(usings, t))
.ToArray();
private static bool NamespaceInUsings(IEnumerable<string> usings, INamedTypeSymbol type) =>
usings.Contains(GetFullName(type.ContainingNamespace, n => !n.IsGlobalNamespace, n => n.ContainingNamespace));
private static bool NameMatches(INamedTypeSymbol type, IdentifierNameSyntax nameSyntax)
{
var isVerbatim = nameSyntax.Identifier.Text.StartsWith("@");
var name = nameSyntax.Identifier.ValueText;
var names = isVerbatim ? new[] { name } : new[] { name, name + "Attribute" };
var fullName = GetFullName(type, t => t != null, t => t.ContainingType);
var res = names.Contains(fullName, StringComparer.Ordinal);
return res;
}
private static string GetFullName<TSymbol>(TSymbol symbol, Func<TSymbol, bool> condition, Func<TSymbol, TSymbol> transition) where TSymbol : ISymbol
{
var values = new List<string>();
while (condition(symbol))
{
values.Add(symbol.Name);
symbol = transition(symbol);
}
values.Reverse();
return string.Join(".", values);
}
private static IEnumerable<INamedTypeSymbol> GetAttributes(IEnumerable<INamedTypeSymbol> types) =>
types.Where(type => IsAttribute(type));
private static IEnumerable<INamedTypeSymbol> GetNonAttributes(IEnumerable<INamedTypeSymbol> types) =>
types.Where(type => !IsAttribute(type));
private static bool IsAttribute(INamedTypeSymbol type) =>
type == null ?
false :
type.ContainingNamespace.Name.Equals("System", StringComparison.Ordinal) &&
type.Name.Equals("Attribute", StringComparison.Ordinal) ||
IsAttribute(type.BaseType);
private static string GetPart(string description, IEnumerable<INamedTypeSymbol> types)
{
var part = string.Join(", ", types.Select(type => $"'{type}'"));
if (!part.Equals(string.Empty))
part = $"{description} {part}";
return part;
}
}
代码修复提供者可以是:
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AmbiguityAnalysisCodeFixProvider)), Shared]
public class AmbiguityAnalysisCodeFixProvider : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds =>
ImmutableArray.Create(AmbiguityAnalysisAnalyzer.DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider() =>
WellKnownFixAllProviders.BatchFixer;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var diagnostic = context.Diagnostics.First();
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var attribute =
root
.FindToken(diagnostic.Location.SourceSpan.Start)
.Parent
.AncestorsAndSelf()
.OfType<AttributeSyntax>()
.First();
foreach(var suggestion in diagnostic.Properties)
{
var title = $"'{suggestion.Value}' to '{suggestion.Key}'";
context.RegisterCodeFix(
CodeAction.Create(
title: title,
createChangedSolution: c => ReplaceAttributeAsync(context.Document, attribute, suggestion.Key, c),
equivalenceKey: title),
diagnostic);
}
}
private static async Task<Solution> ReplaceAttributeAsync(Document document, AttributeSyntax oldAttribute, string suggestion, CancellationToken cancellationToken)
{
var name = SyntaxFactory.ParseName(suggestion);
var newAttribute = SyntaxFactory.Attribute(name);
var root = await document.GetSyntaxRootAsync().ConfigureAwait(false);
root = root.ReplaceNode(oldAttribute, newAttribute);
return document.Project.Solution.WithDocumentSyntaxRoot(document.Id, root);
}
}
试试下面的代码来分析一下:
using System;
using Alpha;
using Alpha.Middle;
using Alpha.Middle.Omega;
using Beta;
public class Horse { }
namespace N
{
[Horse]
class C { }
}
namespace Alpha
{
public class Horse : Attribute { }
namespace Middle
{
public class Horse { }
namespace Omega
{
public class Horse : Attribute { }
}
}
}
namespace Beta
{
public enum Horse { }
public class Foo
{
public class Horse : Attribute { }
}
}
它给出错误:
CS0616 'Horse' 不是属性类
AA0001 可能的属性“Horse”在属性“Alpha.Horse”、“Alpha.Middle.Omega.Horse”和非属性“Horse”、“Alpha.Middle.Horse”、“Beta.Horse”之间不明确
建议的修复方法是:
“马”到“Alpha.Horse”
“马”到“Alpha.Middle.Omega.Horse”