Skip to content

Commit

Permalink
Better handling of nested types in REFL016
Browse files Browse the repository at this point in the history
  • Loading branch information
JohanLarsson committed May 16, 2020
1 parent fb86501 commit ab2f038
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 11 deletions.
52 changes: 42 additions & 10 deletions ReflectionAnalyzers.Tests/REFL016UseNameofTests/CodeFix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}";
Expand Down Expand Up @@ -537,10 +537,7 @@ protected void M1() { }
class Nested
{
void M2()
{
typeof(C).GetMethod(↓""M1"");
}
object P => typeof(C).GetMethod(↓""M1"");
}
}
}";
Expand All @@ -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);
}
}
}
3 changes: 2 additions & 1 deletion ReflectionAnalyzers/Helpers/NameOf.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 } ||
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit ab2f038

Please sign in to comment.