问题
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 IEnumerable
s 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