IEnumerable, requires two implementations?

I am studying the implementation of interfaces and generics, I made this code, but VStudio says that I did not implement System.Collections.Enumerable.GetEnumerator (). Didn't I do this below in general? Does he want two implementations?

namespace Generic_cars { class VehicleLot:IEnumerable<Vehicle> { public List<Vehicle> Lot = new List<Vehicle>(); IEnumerator<Vehicle> IEnumerable<Vehicle>.GetEnumerator() { foreach (Vehicle v in Lot) { yield return v; }; } } } 
+7
source share
3 answers

You implement IEnumerable<Vehicle> , a generic interface that is strongly typed to store Vehicle objects. This interface, however, derives from an earlier IEnumerable interace, which is not shared, and is typed to hold object object .

If you want to implement a generic version (what you are doing), you also need to implement a non-generic version. Typically, you implement a non-generic GetEnumerator by simply invoking the generic version.

In addition, you probably do not want to explicitly implement GetEnumerator<Vehicle> like you do; this will require you to explicitly use your objects for IEnumerable<Vehicle> to use them. Instead, you probably want to do this:

 public IEnumerator<Vehicle> GetEnumerator() { foreach( Vehicle item in items ) { yield return item; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } 
+7
source

Why don't you just do it and your life will be good.

 class VehicleLot : List<Vehicle> { } 

VehicleLot is now your collection class. You can perform any operation, as in any other collection.

Using:

 VehicleLot list = new VehicleLot(); list.Add(new Vehicle()); // you can add as many Vehicles as you want 
+1
source

This is usually better if your class does not implement IEnumerable. You can simply create a property and return your list as IEnumerable:

 namespace Generic_cars { class VehicleLot { public List<Vehicle> Lot = new List<Vehicle>(); IEnumerable<Vehicle> Vehicles { return Lot; } } } 
+1
source

All Articles