I have two interfaces, a generic and a non-generic that have an inheritence hierarchy:
public interface IGenericRelation<TParent, TChild> : IRelation
public interface IRelation
The generic one is implemented by several server controls that are loaded dynamically and I wish to enumerate on the collection of controls that implement this interface. I can do the following
foreach (IRelation relationControl in this.uiPlhControls.Controls.OfType<IRelation)
{ ... }
But what I’d really like to be able to do is…
foreach (IGenericRelation<,> relationControl in this.uiPlhControls.Controls.OfType<IGenericRelation<,>)
{ ... }
and then be able to use the relationControl with the types that it supplied as then I’d have access to the strongly-typed properties available on IGenericRelation. Unfortunately this isn’t possible as it seems I can’t omit the type parameters.
Does anyone know a way to enumerate the controls that implement a generic interface to prevent me having to write several loops instead of one? Using reflection perhaps?
This isn’t possible, as
IGenericRelation<T,F>is a completely distinct type fromIGenericRelation<G,I>. If you need access to particular properties that are common to allIGenericRelation‘s, then you’ll either need to implement them at theIRelationlayer, or introduce a third interface betweenIRelationandIGenericRelation<,>that implements these. The reason for this is that the compiler has no means by which to infer what types to expect it to implement.The easiest way to go about this is to implement your two properties as an
objectat the higher level (eitherIRelationor an intermediate interface) and strongly typed at theIGenericRelation<,>level.