diff --git a/ReflectionAnalyzers.Tests/REFL016UseNameofTests/CodeFix.cs b/ReflectionAnalyzers.Tests/REFL016UseNameofTests/CodeFix.cs index 333c196b..95abea62 100644 --- a/ReflectionAnalyzers.Tests/REFL016UseNameofTests/CodeFix.cs +++ b/ReflectionAnalyzers.Tests/REFL016UseNameofTests/CodeFix.cs @@ -316,7 +316,7 @@ class C { public C() { - var member = typeof(AggregateException).GetProperty(nameof(Exception.Message), BindingFlags.Public | BindingFlags.Instance); + var member = typeof(AggregateException).GetProperty(nameof(AggregateException.Message), BindingFlags.Public | BindingFlags.Instance); } } }"; @@ -537,10 +537,7 @@ protected void M1() { } class Nested { - void M2() - { - typeof(C).GetMethod(↓""M1""); - } + object P => typeof(C).GetMethod(↓""M1""); } } }"; @@ -554,16 +551,51 @@ protected void M1() { } class Nested { - void M2() - { - typeof(C).GetMethod(nameof(C.M1)); - } + object P => typeof(C).GetMethod(nameof(C.M1)); } } }"; RoslynAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, before, after); } + + [Test] + public static void InNestedTypeWhenInheritance() + { + var @base = @" +namespace N +{ + class Base + { + protected void M1() { } } -} +}"; + var before = @" +namespace N +{ + class C : Base + { + class Nested + { + object P => typeof(C).GetMethod(↓""M1""); + } + } +}"; + + var after = @" +namespace N +{ + class C : Base + { + class Nested + { + object P => typeof(C).GetMethod(nameof(C.M1)); + } + } +}"; + + RoslynAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, new[] { @base, before }, after); + } + } +} diff --git a/ReflectionAnalyzers/Helpers/NameOf.cs b/ReflectionAnalyzers/Helpers/NameOf.cs index 2ebb6950..d271ac0c 100644 --- a/ReflectionAnalyzers/Helpers/NameOf.cs +++ b/ReflectionAnalyzers/Helpers/NameOf.cs @@ -16,6 +16,7 @@ internal static bool TryGetExpressionText(ReflectedMember member, SyntaxNodeAnal { targetName = null; if (member.Symbol is null || + member.ReflectedType is null || !member.Symbol.CanBeReferencedByName || !context.SemanticModel.IsAccessible(context.Node.SpanStart, member.Symbol) || member.Symbol is INamedTypeSymbol { IsGenericType: true } || @@ -57,7 +58,7 @@ member.Symbol is ITypeSymbol || return true; } - targetName = $"{TypeOfString(member.Symbol.ContainingType)}.{member.Symbol.Name}"; + targetName = $"{TypeOfString(member.ReflectedType)}.{member.Symbol.Name}"; return true; string TypeOfString(ITypeSymbol t)