Is it possible to override IEnumerable in VC++/CLI?

六眼飞鱼酱① 提交于 2019-12-10 18:21:43

问题


I have an interface which returns an IEnumerable, and I want to implement this in VC++/CLI because the data comes from a third-party unmanaged DLL.

So far I have:

public ref class MyEnumerable : IEnumerable<SomeType^> {
public:
    virtual IEnumerator<SomeType^>^ GetEnumerator();
}

But the compiler complains with C2393: "Covariant returns types are not supported in managed types".

Does that mean that I cannot implement IEnumerables in C++, or is there a workaround?


回答1:


Yikes, it is an awfully clumsy error message. What it is really complaining about is the missing implementation of the non-generic System::Collections::IEnumerable::GetEnumerator() method. You must implement it because the generic IEnumerable<> interface inherits the non-generic one. Something that made sense when generics were first added in .NET 2.0, not so much today. We're kinda stuck with the .NET 1.x legacy.

Otherwise easy to do when you activate your secret decoder ring, make it look like this:

public ref class MyEnumerable : IEnumerable<SomeType^> {
public:
    virtual IEnumerator<SomeType^>^ GetEnumerator();
private:
    virtual System::Collections::IEnumerator^ GetEnumerator1x() 
               = System::Collections::IEnumerable::GetEnumerator {
        return GetEnumerator();
    }
};


来源:https://stackoverflow.com/questions/30937623/is-it-possible-to-override-ienumerable-in-vc-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!