我在C++/CLI的自定义集合类中实现IEnumerable<T>
时遇到问题。这里是代码的相关部分:在C++/CLI中实现IEnumerable <T>
using namespace System::Collections::Generic;
ref class MyCollection : IEnumerable<MyClass^>
{
public:
MyCollection()
{
}
virtual IEnumerator<MyClass^>^ GetEnumerator()
{
return nullptr;
}
};
在编译时,这会导致以下错误:
错误C2392: “系统::收藏集::一般:: IEnumerator的 ^ MyCollection的:: GetEnumerator(void)': covariant返回类型不是受管理类型支持的 ,否则 'System :: Collections :: IEnumerator ^ System :: Collections :: IEnumerable :: GetEnumerator(void)' 将被覆盖错误C3766: 'MyCollection的' 必须为接口 方法 提供一种 执行 '系统::类别:: IEnumerator的 ^系统::类别::的IEnumerable ::的GetEnumerator(无效)'
这是有意义的,因为IEnumerable<T>
来自IEnumerable
。但是,我不知道如何解决这个编译错误。如果这是C#,我会隐式实现IEnumerable
,但我不知道怎么做,在C++/CLI(如果这甚至有可能)是这样的:
class MyCollection : IEnumerable<MyClass>
{
public MyCollection()
{
}
public IEnumerator<MyClass> GetEnumerator()
{
return null;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
如果我加IEnumerable::GetEnumerator()
的实现,编译器抱怨两种方法只有返回类型不同(这也是有道理的)。
那么,如何在C++/CLI类中实现IEnumerable<T>
?
相关http://stackoverflow.com/questions/3609967/c-cli-is-overloading-on-return-type-only-possible – 2011-02-09 11:36:25