Getting all types that implement an interface

前端 未结 17 1019
不思量自难忘°
不思量自难忘° 2020-11-22 00:34

Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?

This is what I want to re-

相关标签:
17条回答
  • 2020-11-22 01:13

    This worked for me. It loops though the classes and checks to see if they are derrived from myInterface

     foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                     .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {
        //do stuff
     }
    
    0 讨论(0)
  • 2020-11-22 01:13

    I got exceptions in the linq-code so I do it this way (without a complicated extension):

    private static IList<Type> loadAllImplementingTypes(Type[] interfaces)
    {
        IList<Type> implementingTypes = new List<Type>();
    
        // find all types
        foreach (var interfaceType in interfaces)
            foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())
                try
                {
                    foreach (var currentType in currentAsm.GetTypes())
                        if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)
                            implementingTypes.Add(currentType);
                }
                catch { }
    
        return implementingTypes;
    }
    
    0 讨论(0)
  • 2020-11-22 01:15

    There are many valid answers already but I'd like to add anther implementation as a Type extension and a list of unit tests to demonstrate different scenarios:

    public static class TypeExtensions
    {
        public static IEnumerable<Type> GetAllTypes(this Type type)
        {
            var typeInfo = type.GetTypeInfo();
            var allTypes = GetAllImplementedTypes(type).Concat(typeInfo.ImplementedInterfaces);
            return allTypes;
        }
    
        private static IEnumerable<Type> GetAllImplementedTypes(Type type)
        {
            yield return type;
            var typeInfo = type.GetTypeInfo();
            var baseType = typeInfo.BaseType;
            if (baseType != null)
            {
                foreach (var foundType in GetAllImplementedTypes(baseType))
                {
                    yield return foundType;
                }
            }
        }
    }
    

    This algorithm supports the following scenarios:

    public static class GetAllTypesTests
    {
        public class Given_A_Sample_Standalone_Class_Type_When_Getting_All_Types
            : Given_When_Then_Test
        {
            private Type _sut;
            private IEnumerable<Type> _expectedTypes;
            private IEnumerable<Type> _result;
    
            protected override void Given()
            {
                _sut = typeof(SampleStandalone);
    
                _expectedTypes =
                    new List<Type>
                    {
                        typeof(SampleStandalone),
                        typeof(object)
                    };
            }
    
            protected override void When()
            {
                _result = _sut.GetAllTypes();
            }
    
            [Fact]
            public void Then_It_Should_Return_The_Right_Type()
            {
                _result.Should().BeEquivalentTo(_expectedTypes);
            }
        }
    
        public class Given_A_Sample_Abstract_Base_Class_Type_When_Getting_All_Types
            : Given_When_Then_Test
        {
            private Type _sut;
            private IEnumerable<Type> _expectedTypes;
            private IEnumerable<Type> _result;
    
            protected override void Given()
            {
                _sut = typeof(SampleBase);
    
                _expectedTypes =
                    new List<Type>
                    {
                        typeof(SampleBase),
                        typeof(object)
                    };
            }
    
            protected override void When()
            {
                _result = _sut.GetAllTypes();
            }
    
            [Fact]
            public void Then_It_Should_Return_The_Right_Type()
            {
                _result.Should().BeEquivalentTo(_expectedTypes);
            }
        }
    
        public class Given_A_Sample_Child_Class_Type_When_Getting_All_Types
            : Given_When_Then_Test
        {
            private Type _sut;
            private IEnumerable<Type> _expectedTypes;
            private IEnumerable<Type> _result;
    
            protected override void Given()
            {
                _sut = typeof(SampleChild);
    
                _expectedTypes =
                    new List<Type>
                    {
                        typeof(SampleChild),
                        typeof(SampleBase),
                        typeof(object)
                    };
            }
    
            protected override void When()
            {
                _result = _sut.GetAllTypes();
            }
    
            [Fact]
            public void Then_It_Should_Return_The_Right_Type()
            {
                _result.Should().BeEquivalentTo(_expectedTypes);
            }
        }
    
        public class Given_A_Sample_Base_Interface_Type_When_Getting_All_Types
            : Given_When_Then_Test
        {
            private Type _sut;
            private IEnumerable<Type> _expectedTypes;
            private IEnumerable<Type> _result;
    
            protected override void Given()
            {
                _sut = typeof(ISampleBase);
    
                _expectedTypes =
                    new List<Type>
                    {
                        typeof(ISampleBase)
                    };
            }
    
            protected override void When()
            {
                _result = _sut.GetAllTypes();
            }
    
            [Fact]
            public void Then_It_Should_Return_The_Right_Type()
            {
                _result.Should().BeEquivalentTo(_expectedTypes);
            }
        }
    
        public class Given_A_Sample_Child_Interface_Type_When_Getting_All_Types
            : Given_When_Then_Test
        {
            private Type _sut;
            private IEnumerable<Type> _expectedTypes;
            private IEnumerable<Type> _result;
    
            protected override void Given()
            {
                _sut = typeof(ISampleChild);
    
                _expectedTypes =
                    new List<Type>
                    {
                        typeof(ISampleBase),
                        typeof(ISampleChild)
                    };
            }
    
            protected override void When()
            {
                _result = _sut.GetAllTypes();
            }
    
            [Fact]
            public void Then_It_Should_Return_The_Right_Type()
            {
                _result.Should().BeEquivalentTo(_expectedTypes);
            }
        }
    
        public class Given_A_Sample_Implementation_Class_Type_When_Getting_All_Types
            : Given_When_Then_Test
        {
            private Type _sut;
            private IEnumerable<Type> _expectedTypes;
            private IEnumerable<Type> _result;
    
            protected override void Given()
            {
                _sut = typeof(SampleImplementation);
    
                _expectedTypes =
                    new List<Type>
                    {
                        typeof(SampleImplementation),
                        typeof(SampleChild),
                        typeof(SampleBase),
                        typeof(ISampleChild),
                        typeof(ISampleBase),
                        typeof(object)
                    };
            }
    
            protected override void When()
            {
                _result = _sut.GetAllTypes();
            }
    
            [Fact]
            public void Then_It_Should_Return_The_Right_Type()
            {
                _result.Should().BeEquivalentTo(_expectedTypes);
            }
        }
    
        public class Given_A_Sample_Interface_Instance_Type_When_Getting_All_Types
            : Given_When_Then_Test
        {
            private Type _sut;
            private IEnumerable<Type> _expectedTypes;
            private IEnumerable<Type> _result;
    
            class Foo : ISampleChild { }
    
            protected override void Given()
            {
                var foo = new Foo();
                _sut = foo.GetType();
    
                _expectedTypes =
                    new List<Type>
                    {
                        typeof(Foo),
                        typeof(ISampleChild),
                        typeof(ISampleBase),
                        typeof(object)
                    };
            }
    
            protected override void When()
            {
                _result = _sut.GetAllTypes();
            }
    
            [Fact]
            public void Then_It_Should_Return_The_Right_Type()
            {
                _result.Should().BeEquivalentTo(_expectedTypes);
            }
        }
    
        sealed class SampleStandalone { }
        abstract class SampleBase { }
        class SampleChild : SampleBase { }
        interface ISampleBase { }
        interface ISampleChild : ISampleBase { }
        class SampleImplementation : SampleChild, ISampleChild { }
    }
    
    0 讨论(0)
  • 2020-11-22 01:15

    OfType Linq method can be used exactly for this kind of scenarios:

    https://docs.microsoft.com/fr-fr/dotnet/api/system.linq.enumerable.oftype?view=netframework-4.8

    0 讨论(0)
  • 2020-11-22 01:16

    To find all types in an assembly that implement IFoo interface:

    var results = from type in someAssembly.GetTypes()
                  where typeof(IFoo).IsAssignableFrom(type)
                  select type;
    

    Note that Ryan Rinaldi's suggestion was incorrect. It will return 0 types. You cannot write

    where type is IFoo
    

    because type is a System.Type instance, and will never be of type IFoo. Instead, you check to see if IFoo is assignable from the type. That will get your expected results.

    Also, Adam Wright's suggestion, which is currently marked as the answer, is incorrect as well, and for the same reason. At runtime, you'll see 0 types come back, because all System.Type instances weren't IFoo implementors.

    0 讨论(0)
  • 2020-11-22 01:16

    Even better when choosing the Assembly location. Filter most of the assemblies if you know all your implemented interfaces are within the same Assembly.DefinedTypes.

    // We get the assembly through the base class
    var baseAssembly = typeof(baseClass).GetTypeInfo().Assembly;
    
    // we filter the defined classes according to the interfaces they implement
    var typeList = baseAssembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(IMyInterface))).ToList();
    

    By Can Bilgin

    0 讨论(0)
提交回复
热议问题