Git Product home page Git Product logo

reflectionanalyzers's Introduction

DotNetAnalyzers

This project is for the community to make a common code base of .NET code analyzers using the new VS14 code analyzer functionality. Overview

reflectionanalyzers's People

Contributors

dependabot[bot] avatar djack42 avatar erikwahlstrom avatar gitter-badger avatar iqv-csis avatar jaggedspire avatar jnm2 avatar johanlarsson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

reflectionanalyzers's Issues

Handle shadowing

class Foo
{
    public new string ToString() => string.Empty;
}

When doing GetMethod, check flags etc.

REFL005 should not care about Instance and Static in GetNestedType

namespace RoslynSandbox
{
    using System.Reflection;
    using NUnit.Framework;

    class Foo
    {
        internal static class Bar
        {
        }
    }

    class Tests
    {
        [Test]
        public void SomeTest()
        {
            Assert.NotNull(typeof(Foo).GetNestedType(nameof(Foo.Bar), BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
        }
    }
}

The msdn docs are not awesome here:

A bitmask comprised of one or more BindingFlags that specify how the search is conducted.

Handle more cases than when GetX is called on a typeof()

Today we only check typeof(Foo).GetMethod("Bar") for simplicity.

var method = obj.GetType().GetMethod("Bar");
var type = typeof(Foo);
var method = .GetMethod("Bar");

Are two other common cases, we walk a bit and try to find out the type.

Suggest GetCustomAttribute<T>

GetCustomAttribute<FooAttribute>() instead of (FooAttribute)GetCustomAttribute(typeof(FooAttribute))โ€”I keep seeing this.

GetNestedType when nested is declared in base type.

Given:

class Foo : Base
{
}

public class Base
{
    public static class PublicStatic
    {
    }

    public class Public
    {
    }

    private static class PrivateStatic
    {
    }

    private class Private
    {
    }
}

Does GetNestedType always return null?

var type = typeof(Foo).GetNestedType(nameof(Public), BindingFlags.Public | BindingFlags.FlattenHierarchy)

Suggest BindingFlags.DoNotWrapExceptions

๐Ÿ’ญ This is .NET Core 2.1 only. If the project targets anything else, perhaps suggest creating and invoking a typed delegate in order to avoid wrapping with TargetInvocationException?

Invoke generic method definition.

Before:

class Foo
{
    public Foo()
    {
        var methodInfo = typeof(Foo).GetMethod(nameof(this.Id)) 
                                    .Invoke(null, new object[] { 1 }); 
    }
    public T Id<T>(T value) => value;
}

After:

class Foo
{
    public Foo()
    {
        var methodInfo = typeof(Foo).GetMethod(nameof(this.Id))
                                    .MakeGenericMethod(typeof(int)) 
                                    .Invoke(null, new object[] { 1 });
    }
    public T Id<T>(T value) => value;
}

Suggest null instead of empty object arrays

methodInfo.Invoke(null, Array.Empty<object>()) should really be methodInfo.Invoke(null, null), constructorInfo.Invoke(new object[0]) should be constructorInfo.Invoke(null), etc.

Codefix/refactoring: generate cached delegate for methodInfo.Invoke

Before:

namespace RoslynSandbox
{
    using System;
    using System.Reflection;
    using System.Windows.Controls;

    class C
    {
        private static readonly Type TemplatedAdornerType = typeof(AdornedElementPlaceholder).Assembly.GetType("MS.Internal.Controls.TemplatedAdorner", throwOnError: true);
        private static readonly MethodInfo ClearChildMethod = TemplatedAdornerType.GetMethod("ClearChild");
    }
}

After:

namespace RoslynSandbox
{
    using System;
    using System.Reflection;
    using System.Windows.Controls;

    class C
    {
        private static readonly Type TemplatedAdornerType = typeof(AdornedElementPlaceholder).Assembly.GetType("MS.Internal.Controls.TemplatedAdorner", throwOnError: true);
        private static readonly Action<Adorner> ClearChildMethod = (Action<Adorner>)Delegate.CreateDelegate(typeof(Action<Adorner>), TemplatedAdornerType.GetMethod("ClearChild"), throwOnBindFailure: true);
    }
}

Replace GetGenericArguments with GenericTypeArguments or GenericTypeParameters

Not sure about this one, but I picked up on this at https://github.com/dotnet/corefx/issues/23762#issuecomment-327223953 and also on a similar issue a long time ago.

GetGenericArguments() returns parameters (not arguments) if the type is a generic definition, and it returns arguments if the type is a constructed generic.

GenericTypeArguments is better if you expect the type to be constructed.
GenericTypeParameters is better if you expect the type to be a definition. It only exists after adding .GetTypeInfo() though.
If you don't have an expectation about constructed vs definition, I'm not sure how you can meaningfully use GetGenericArguments().

AD0001

Severity	Code	Description	Project	File	Line	Suppression State
Warning	AD0001	Analyzer 'ReflectionAnalyzers.GetMethodAnalyzer' threw an exception of type 'System.IO.FileNotFoundException' with message 'Could not load file or assembly 'System.Reflection.TypeExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'.	Gu.Xml	C:\Git\Gu.Xml\Gu.Xml\CSC	1	Active

Analyzer: missing bindingflags

Before:

namespace RoslynSandbox
{
    using System.Reflection;

    class Foo
    {
        public Foo()
        {
            var methodInfo = typeof(Foo).GetMethod(nameof(this.Bar);
        }

        public static void Bar()
        {
        }
    }
}

After:

namespace RoslynSandbox
{
    using System.Reflection;

    class Foo
    {
        public Foo()
        {
            var methodInfo = typeof(Foo).GetMethod(
                nameof(this.Bar),
                BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
        }

        public static void Bar()
        {
        }
    }
}

Warn on generic type names in GetInterface

Generic interface types may be implemented multiple times.

Refactor to .FirstOrDefault(interfaceType => interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == ...)

REFL006 only warn for types in assembly

I have encountered a situation in the past where public vs private depended on the version of the framework the code was running against. (using reflection to access a private member that was later made public)

Maybe warn for types in sln?

GetX private static on declaring type

class Foo
{
    private static readonly int Value;
}

class Bar : Foo
{
}

Before:

typeof(Bar).GetField("Value", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy)

After:

typeof(Foo).GetField("Value", BindingFlags.NonPublic | BindingFlags.Static)

Suggest searching on the declaring type

Instead of relying on hierarchy flattening of public members and walking the inheritance chain. Also could suggest BindingFlags.DeclaredOnly for perf if that doesn't make the reflection reasoning too brittle.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.