我如何枚举实现一个通用接口的所有项目? [英] How do I enumerate all items that implement a generic interface?

查看:198
本文介绍了我如何枚举实现一个通用接口的所有项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个接口,一个通用和非通用有一个传承的层次结构:

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<,>)
    { ... }

然后就可以使用 relationControl 与它提供的各类那么我有机会在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?

推荐答案

这是不可能的,因为 IGenericRelation< T,F> IGenericRelation℃的完全不同的类型; G,I> 。如果你需要访问通用于所有特殊属性的,那么你要么需要在 IRelation IGenericRelation C $ C>层,或引入 IRelation IGenericRelation℃之间的第三个接口;,> 实现这些。这样做的原因是,编译器没有手段来推断期望它来实现什么类型。

This isn't possible, as IGenericRelation<T,F> is a completely distinct type from IGenericRelation<G,I>. If you need access to particular properties that are common to all IGenericRelation's, then you'll either need to implement them at the IRelation layer, or introduce a third interface between IRelation and IGenericRelation<,> 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.

去这个最简单的方法是实现你的两个属性,一个对象在较高的水平(无论是 IRelation 或中间接口),并极力在 IGenericRelation<类型;,> 级别

The easiest way to go about this is to implement your two properties as an object at the higher level (either IRelation or an intermediate interface) and strongly typed at the IGenericRelation<,> level.

这篇关于我如何枚举实现一个通用接口的所有项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆