Kiggede lidt rundt, og fandt ud af, at du kan nøjes med én metode, hvis du bruger Reflection:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Vehicle> vehicles = new List<Vehicle>();
vehicles.Add(new Car());
vehicles.Add(new Car());
vehicles.Add(new Car());
vehicles.Add(new MotorCycle());
vehicles.Add(new MotorCycle());
vehicles.Add(new MotorCycle());
Console.WriteLine(vehicles.Sum(f => f.Wheels));
Console.ReadLine();
foreach (Vehicle vehicle in vehicles)
{
vehicle.InvokeMethod(typeof(Car), vehicle, "RemoveLeftBackTire", null);
vehicle.InvokeMethod(typeof(MotorCycle), vehicle, "RemoveBackTire", null);
}
Console.WriteLine(vehicles.Sum(f => f.Wheels));
Console.ReadLine();
}
}
class Vehicle
{
public int Wheels { get; set; }
public void InvokeMethod(Type type, object classInstance, string methodName, object[] parameters)
{
if (type != null && classInstance.GetType() == type)
{
MethodInfo method = type.GetMethod(methodName);
if (method != null)
{
object result = null;
int parameterCount = method.GetParameters().Length;
if (parameterCount == 0)
{
result = method.Invoke(classInstance, null);
}
else
{
result = method.Invoke(classInstance, parameters);
}
}
}
}
}
class Car : Vehicle
{
public Car()
{
base.Wheels = 4;
}
public void RemoveLeftBackTire()
{
base.Wheels--;
}
public void RemoveRightBackTire()
{
base.Wheels--;
}
}
class MotorCycle : Vehicle
{
public MotorCycle()
{
base.Wheels = 2;
}
public void RemoveBackTire()
{
base.Wheels--;
}
}
}