一个List中包含多个接口;
有没有一种方法可以在像 List 这样的泛型类中定义类型,以包含仅实现多个接口的对象?可能是类类型和接口。
例如:
List<myObjectBase, IDisposable, IClonable> myList;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不确定我是否理解正确,但是这样怎么样:
这样您只能将对象添加到从基础派生的列表中并实现这些接口。
Not sure if I understood correctly, but how about this:
This way you can only add objects to the list which derive from the base and implement those interfaces.
不,在这种情况下,你必须用以下方式表达:
然后你可以写:
No. In that case you would have to express that in the following way:
Then you can write:
不,不支持多个通用参数。
这也没有多大意义。与
ArrayList
之类的类相比,使用通用List
类没有任何好处。您将失去所有类型安全的好处,并且最终仍然不得不将东西扔得到处都是。更好的选择是创建一个复合类来处理您想要做的所有事情...然后使用它:
然后将其用作通用参数:
No, multiple generic parameters are not supported.
It wouldn't make much sense either. There would be no benefit of using the generic
List<T>
class over something like anArrayList
. You would lose all of the type safety benefits and you'd wind up still having to cast things all over the place.The better option would be to create a composite class that handles all of the things you want to do...and then use that:
And then use that as your generic parameter:
一种可能有用的方法是定义一个接口 ISelf。它的一个成员 Self 只是将“this”返回为 T;然后对于任何可能组合的接口 IWhatever ,定义一个通用版本 IWhatever 。它继承了 IWhatever 和 ISelf。在这种情况下,需要实现 IFoo 的类 Whizbang。和IBar将隐式实现 ISelf、IFoo>、IBar> 等。需要同时实现 IFoo 和 IBar 的例程可以接受 IFoo 类型的参数;该参数将实现 IFoo;它的 Self 属性将实现 IBar。使用此模式实现多个接口的任何对象都可以使用以任何顺序列出的部分或全部接口转换为给定形式的嵌套接口类型。
One approach that may be helpful is to define an interface ISelf<out T> whose one member, Self, simply returns "this" as a T; then for any interface IWhatever that might be combined, define a generic version IWhatever<out T> which inherits both the IWhatever and ISelf<T>. In that case, a class Whizbang which implements IFoo<Whizbang> and IBar<Whizbang> will implicitly implement ISelf<Whizbang>, IFoo<IBar<Whizbang>>, IBar<IFoo<Whizbang>>, etc. A routine which needs something that implements both IFoo and IBar can accept a parameter of type IFoo<IBar>; that parameter will implement IFoo; its Self property will implement IBar. Any object which implements multiple interfaces using this pattern may be cast to a nested interface type of the given form using some or all of the interfaces, listed in any order.
下面是添加对我有用的多个接口的最简单的解决方案。
列表 myList = new List()
Below is the simplest solution for adding multiple interfaces that worked for me.
List<ICommonInterface> myList = new List<ICommonInterface>()
您可以使用 ArrayList 并可以检查这个列表中的一个对象 - 也许它更方便。
You can use an ArrayList and can check the Type of an object in this list - maybe it is handier.