I have an interface:
public interface InterfaceA<S,T>{}
and I want to load an instance of all classes that implement this interface, regardless of the generic parameters S and T. So I have a class with a method to do this. The method signature is currently:
public IEnumerable<object> GetInstancesOfImplementingTypes (Type targetType)
to reflect through the loaded assemblies looking for types that have a GetGenericTypeDefinition equal to the GetGenericTypeDefinition of the targetType. I’m using the type (rather than having a T param on the method) so that I don’t have to specify the generic arguments, ie I can call it like so:
var foundinstances = o.GetInstancesOfImplementingTypes(typeof(InterfaceA<,>))
But I seem to have to return the instances of the found types as objects. is there some way that I can return a more constrained type than just object, as I know all the instances will be some implementation of InterfaceA, I just don’t know what S and T will be.
No. Different instantiations of
InterfaceA<S,T>are unrelated as far as the CLR is concerned, so unless they have a non-generic common base you must use object.If there are some members in InterfaceA that don’t depend on the type arguments and that you wish to access irregardless of S and T, you may wish to create another non-generic interface that InterfaceA inherits from containing only those members.