C#关于循环/切换语句的适当性。如何在switch语句中使用arrayList?

时间:2015-09-13 12:18:35

标签: c# if-statement arraylist switch-statement refactoring

第一个问题是关于编程实践是否更好,将其保留为IF语句,或将其更改为switch语句。

 public Booking bookVehicle(String vehicleClass, Client potentialClient, int number)
    {
        ArrayList vehicles;
        if (vehicleClass.Equals("a", StringComparison.OrdinalIgnoreCase))
            vehicles = thisLocation.getVehicleClass("Prestige Sedan");
        else if (vehicleClass.Equals("b", StringComparison.OrdinalIgnoreCase))
            vehicles = thisLocation.getVehicleClass("Luxury Sedan");
        else if (vehicleClass.Equals("c", StringComparison.OrdinalIgnoreCase))
            vehicles = thisLocation.getVehicleClass("Full-size Sedan");
        else if (vehicleClass.Equals("d", StringComparison.OrdinalIgnoreCase))
            vehicles = thisLocation.getVehicleClass("Mid-size Sedan");
        else if (vehicleClass.Equals("e", StringComparison.OrdinalIgnoreCase))
            vehicles = thisLocation.getVehicleClass("Hatchback");
        else if (vehicleClass.Equals("f", StringComparison.OrdinalIgnoreCase))
            vehicles = thisLocation.getVehicleClass("Compact");
        else vehicles = thisLocation.getVehicleClass("Compact");

        if (available(vehicles, number))
        {
            ArrayList hiredVehicles = new ArrayList();
            int currentVehicle = 0;
            int hireCharge = 0;
            while (number > 0)
            {
                Vehicle thisVehicle = (Vehicle)vehicles[currentVehicle];
                if (!thisVehicle.hired)
                {
                    hiredVehicles.Add(thisVehicle);
                    hireCharge += thisVehicle.hireFee;
                    number--;
                }
                currentVehicle++;
            }
            return new Booking(potentialClient, hireCharge, hiredVehicles);
        }
        else
        {
            return new Booking(potentialClient, false);
        }
    }

因此上面的代码正在评估车辆的ArrayList,车辆的一个属性是使用IF语句的“车辆类”。是否更好地使用Switch语句为什么/为什么不?

下面是我的代码尝试实现与上面相同的功能,但有一个switch语句,将它放入一个单独的方法被调用,但我不知道如何使用arrayList。

    switch (ArrayList vehicles)
{
    case 'a':
        vehicles = thislocation.getVehicleClass("prestige Sedan");
        break;
    case 'b':
        vehicles = thisLocation.getVehicleClass("Luxury Sedan");
        break;
    case 'c':
        vehicles = thisLocation.getVehicleClass("Full-size Sedan");
        break;
    case 'd':
        vehicles = thisLocation.getVehicleClass("Mid-size Sedan");
        break;
    case 'e':
        vehicles = thisLocation.getVehicleClass("Hatchback");
        break;
    case 'f':
        vehicles = thisLocation.getVehicleClass("Compact");
        break;
        default:
    vehicles = thisLocation.getVehicleClass("Compact");
        break;
return vehicles;
}

如果你能帮我把这个switch语句设置为与if语句相同的功能(如果可能/适当的话)id非常感谢。

0 个答案:

没有答案