开发者

Can I return all generic objects that are of a particular generic type?

开发者 https://www.devze.com 2023-03-11 05:23 出处:网络
I have an interface: public interface InterfaceA<S,T>{} and I want to load an instance of all classes that implement this interface, regardle开发者_运维技巧ss of the generic parameters S and

I have an interface:

public interface InterfaceA<S,T>{}

and I want to load an instance of all classes that implement this interface, regardle开发者_运维技巧ss 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.


No. There is no way in .Net to declare an instance which is typed to InteraceA<,> or any generic type where the parameters are omitted.

One way to work around this though is to break up the interface into 2 interfaces. One which is non-generic and contains the methods which are not specific to the generic parameters and the other which is generic and contains the methods that are. Then create an inheritance relationship between those types. For example

interface InterfaceA {
  void SomeOperation(); 
}
interface InterfaceA<T, S> : InterfaceA {
  T SomeOtherOperation(S p1); 
}

This allows you to observe the result of your query as instances of InterfaceA via the Cast extension method

var foundinstances = o
  .GetInstancesOfImplementingTypes(typeof(InterfaceA<,>))
  .Cast<InterfaceA>();
0

精彩评论

暂无评论...
验证码 换一张
取 消