mercredi 26 août 2020

Getting All Generic Types in C# from an Assembly

I need to get a list of generic types of a library to filter them for certain traits. I'm trying to test if an interface implementation implements the interface contract correctly, and try to list all types that inherit from that interface, but the interface contains a generic parameter.

The issue that I think this approach has is that if a test/assembly does not generate an instance of the generic type, it will not contain a reference to that type.

I have already found:

  • this does not give me the posibility to look for types, unless I know the type: C# get the the type Generic<T> given T
  • getting all types from an assembly does not include generic types, I made a test case below that proves this fact.
    public class MyClass<T>
    {
        public T t { get; set; }

        public MyClass(T t)
        {
            this.t = t;
        }
    }

    public class SimpleTest
    {

        [Fact]
        public void TestCreateMyClass()
        {
            var types = AppDomain.CurrentDomain.GetAssemblies()
                                 .SelectMany(s => s.GetTypes())
                                 .Where(p => p.GetType().FullName.Contains("MyClass")).ToArray();
            Assert.NotEmpty(types); // fails
        }
    }

My current workaround for this is to explicitly list all classes of that type to make a check, but I would prefer some automated way as people are expected to extend this functionality and I want them to be automatically tested.





Aucun commentaire:

Enregistrer un commentaire