IDontGetIt.NET/CLI
So, I want to implement the generic ICollection
generic<typename T>ref class ItemCollection : ICollection<T>
Let's have a look at the generic ICollection interface:
generic<typename T>public interface ICollection : IEnumerable<T> , IEnumerable
So as we see, we have to deal with one old-fashion enumerable- and one generic enumerable interface. This first defines the method "IEnumerator^ GetEnumerator()", while the generic one defines the "IEnumerator<T>
We all know, that we cannot overload functions that solely differ by return-type. However, as the generic ICollection inherits from both IEnumerables, both GetEnumerators are in fact present in the generic ICollection.
Don't ask me why this can exist at all. The problem comes up when I try to implement the ICollection
How to deal with this? Not really any ideas, lots of C++ compiler errors such as the one with the two functions only differing by return types, or methods not matching certain signaturs etc.
I had a look at the C# way, because the C# refactor does the implementation on it's own:
public IEnumerator<T>
GetEnumerator() System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
Well OK, this looks reasonable by explictly having the "targeted" interface in the method name. But still no idea how this looks in C++/CLI, only silly compiler errors. I looked up the signature in the MSDN reference of some collection classes, but this didn't work out as well.
So, after numerous trial-and-errors attempts, this came out:
public:
virtual IEnumerator<T>^ GetEnumerator();
private:
virtual Collections::IEnumerator^ _GetEnumerator () sealed = Collections::IEnumerable::GetEnumerator
{
return GetEnumerator();
}
No need to mention that I'm seriously unhappy with this. This is everything, but definitly not elegant. I couldn't think of it being that hard to implement ICollection
OK, it's late, no more time to think about this problem.


1 Comments:
Another workaround is to create an intervening base class which resolves the non-generic GetEnumerator() and then have your derived class inherit both the intervening class and the ICollection (or IList) generic interface, providing the generic version of GetEnumerator():
// Non-generic IEnumerable must be handled in a separate class
public ref class _Items : public Collections::IEnumerable
{
public:
virtual Collections::IEnumerator^ GetEnumerator()
{
...
}
};
public ref class Items : public _Items, public IList<Item^>
{
public:
virtual IEnumerator<Item^>^ GetEnumerator() new
{
...
}
};
By
Glenn Slayden, at 10:52 PM
Post a Comment
<< Home