简体   繁体   中英

IEnumerable, requires two implementations?

I am learning about implementing interfaces and generics, I made this code, but VStudio says that I did not implement System.Collections.Enumerable.GetEnumerator(). Did I not do this below, generically? It wants 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; };
    }
 }
}

You are implementing IEnumerable<Vehicle> , a generic interface that is strongly typed to hold Vehicle objects. That interface, however, derives from the older IEnumerable interace that is not generic, and is typed to hold object objects.

If you want to implement the generic version (which you do) you need to also implement the non-generic version. Typically you would implement the non-generic GetEnumerator by simply calling the generic version.

Also, you probably don't want to be explicitly implementing GetEnumerator<Vehicle> the way you are; that will require you to explicitly cast your objects to IEnumerable<Vehicle> in order 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();
}

Why don't you just do this way and your life will be all good.

class VehicleLot : List<Vehicle>
{

}

Now VehicleLot is your collection class. You can do any operation as you do on any other collection.

Usage:

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

Usually it's better when your class doesn't implement IEnumerable itself. You can just 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;
    }
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM