开发者

Finding elements of a given type in an array in C#

I have a Fleet class that contains an array of (base class) Vehicles. The vehicles in the array are subclasses of Vehicles: Plains, Trains and Automobiles. The array is private, but the Fleet class must offer a method to get at the vehicles of a given type.

Something like:

class Fleet
{
    private Vehicle[] _vehicles;

    // returns the vehicles of the specified subclass
    public ???? Get(????)
    {
        return ????
    }
}

Fleet fleet = new Fleet("fleet.def");

Trains[] trains = fleet.Get(Trains); 开发者_运维问答  // looks clean but isn't possible
Plains[] plains = fleet.Get<Plains>(); // looks okay but don't know
                                       //   how to implement

(I'm using arrays, but really any collection type that can be iterated is fine.)

Now, as you can see, I have absolutely no idea how to implement this. I'm looking for an elegant solution for the Get method, efficiency is not really an issue. Please also name the key techniques involved in the solution, so I can look them up in my C# books...

Thanks!


Your Fleet.Get() will look like

public IEnumerable<T> Get<T>()
{
  return _vehicles.OfType<T>();
}


Make it a List<> and use FindAll(x => x.GetType() == typeof(Train)) to get all Train objects from the list.


 public T[] Get<T>() where T : Vehicle
 {
     List<Vehicle> lstVehicles = new List<Vehicle>(_vehicles);
     return lstVehicles.FindAll(delegate(Vehicle vehicle){
         return vehicle.GetType() == typeof(T);
     }).ToArray();
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜