双枚举器,第二个枚举器通过实现时的接口类型冲突
我有一个实现 IList 的泛型类。
public class ListBase<T>: IList<T>, IListBase{
IEnumerator<T> GetEnumerator(){ ....
System.Collections.IEnumerator GetEnumerator(){ return GetEnumerator();}
}
IListBase 是一个接口,用于在运行时不知道 T 类型的情况下访问此类上的方法。
我需要通过这个 IListBase 接口实现第二个枚举器,它将迭代我的类的成员并将它们返回为所有成员将实现的基类型。
我尝试过让 IListBase 实现我的特定枚举器:
public interface IListBase: IEnumerable<MemberBaseType> { ....
但是由于 T 和 MemberBaseType 在某些情况下可能相同,所以这会失败。即使将枚举器成员添加到接口然后使用显式声明也无济于事。
然后,我尝试添加另一种方法来调用仅获取特定的 IEnumerator,但编译器随后抱怨找不到与此类型一起使用的公共 GetEnumerator 方法...
有关添加此辅助枚举器的任何建议,以便它们不会相互冲突?
I have a generic class that implements IList
public class ListBase<T>: IList<T>, IListBase{
IEnumerator<T> GetEnumerator(){ ....
System.Collections.IEnumerator GetEnumerator(){ return GetEnumerator();}
}
The IListBase is an interface I use to access methods on this class for cases where I don't know the type of T at runtime.
I need to implement a second Enumerator via this IListBase interface which will iterate the members of my class and return them cast as a base type that all members will implement.
I've tried having the IListBase implement my specific Enumerator:
public interface IListBase: IEnumerable<MemberBaseType> { ....
But this blows up due to the fact that T and MemberBaseType could be the same in some instances. Even adding the enumerator members to the interface and then using explicit declarations doesnt help this problem.
I then tried adding another method to call for just getting specific IEnumerator, but the compiler then complains about not finding a public GetEnumerator method to use with this type...
Any recommendations for adding this secondary enumerator so they don't collide with each other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在同一级别拥有两个执行不同操作的枚举器(在我看来)是一个坏主意。您可能可以强制它,但是一旦有人强制转换您的类型(特别是如果强制转换为非通用接口),他们将得到的结果很大程度上取决于猜测。
我建议(相反)通过属性提供此功能,例如
.Members
,其中.Members
提供此枚举。这样就不会出现意图模糊的情况,也不会引起编译器的不满。所以我可以使用:您也可以考虑
ITypedList
,它可能在这里有一些相关性,特别是如果您想将数据绑定到您的列表(如果T
则没有必要) > 本身就清楚地定义了一切)。简而言之:
Having two enumerators at the same level that do different things is (IMO) a bad idea. You can probably force it, but as soon as someone casts your type (especially if casting to the non-generic interface) it is largely guesswork which they will get.
I would recommend (instead) making this available via a property, for example
.Members
, where.Members
offers this enumeration. Then no ambiguity of intent, and no compiler unhappiness. So I could use:You might also consider
ITypedList
, which may have some relevence here, especially if you want to data-bind to your list (this isn't necessary ifT
by itself defines everything cleanly).In short: