切换到对象实例

时间:2011-10-31 17:33:27

标签: c# object properties switch-statement

修改

这是一个不同版本的代码,使我更清楚我要做的事情:

class Program
{
    static void Main(string[] args)
    {
        RepairCar(Car.Ferrari);
    }

    public static void RepairCar(Car BrokenCar)
    {
        switch (BrokenCar)
        {
            case Car.Ferrari:
                Console.WriteLine("${0} of Insurance Needed", CalculateInsurance(BrokenCar));
                // 
                // Repair Algorithm Here
                //
                break;

            case Car.BMW:
                Console.WriteLine("${0} of Insurance Needed", CalculateInsurance(BrokenCar));
                // 
                // Repair Algorithm Here
                //
                break;

            case Car.Audi:
                Console.WriteLine("${0} of Insurance Needed", CalculateInsurance(BrokenCar));
                // 
                // Repair Algorithm Here
                //
                break;

            default:
                Console.WriteLine("${0} of Insurance Needed", CalculateInsurance(BrokenCar));
                // 
                // Repair Algorithm Here
                //
                break;
        }
    }

    public static double CalculateInsurance(Car BrokenCar)
    {
        return (BrokenCar.Price / 10);
    }

}

public class Car
{
    public double Price;
    public int MaxSpeed;
    public int MinSpeed;

    public Car(double Price, int MaxSpeed, int MinSpeed)
    {
        this.Price = Price;
        this.MaxSpeed = MaxSpeed;
        this.MinSpeed = MinSpeed;
    }

    public static Car Ferrari = new Car(100000, 250, 10);
    public static Car Audi = new Car(50000, 120, 30);
    public static Car BMW = new Car(35000, 80, 75);
}

如上所述,这将无法编译,因为它不会让我在RepairCar方法中切换BrokenCar。有什么建议吗?

原帖

我正在尝试创建一个可以存储静态属性的对象,更重要的是可以切换 - 这是一个例子 -

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetMaxSpeed(Car.Ferrari));
        Console.ReadLine();
    }

    public static int GetMaxSpeed(Car ModelType)
    {
        switch (ModelType)
        {
            case Car.Ferrari:
                return Car.Ferrari.MaxSpeed;

            case Car.VW:
                return Car.VW.MaxSpeed;

            case Car.AstonMartin:
                return Car.AstonMartin.MaxSpeed;
        }
    }

    public class Car
    {
        public int MinSpeed;
        public int MaxSpeed;

        public Car(int MinSpeed, int MaxSpeed)
        {
            this.MinSpeed = MinSpeed;
            this.MaxSpeed = MaxSpeed;
        }

        public static Car Ferrari = new Car(30, 240);
        public static Car VW = new Car(10, 50);
        public static Car AstonMartin = new Car(75, 180);
    }

}

有没有人有任何想法?

先谢谢!

威廉

修改

此示例描述了一个更大,更复杂的系统。为了说明我需要这样做的原因,请参阅以下更新:

    public static void OnCarSale(Car CarSold)
    {
        double LuxuryTax = 75;

        switch (CarSold)
        {
            case Car.Ferrari:
                Console.WriteLine("Total Price: {0}", Car.Ferrari.Price + LuxuryTax);
                break;

            case Car.VW:
                Console.WriteLine("Total Price: {0}", Car.VW);
                break;

            case Car.AstonMartin:
                Console.WriteLine("Total Price: {0}", Car.Ferrari.Price + LuxuryTax);
                break;
        }
    }

这将由此类之外的事件调用 -

5 个答案:

答案 0 :(得分:6)

这取决于你想用它做什么。如果“开关”是给汽车额外的行为,那就把它放在班级本身。例如,在你的情况下你已经有了相应的字段(ick,public fields,但是......)你可以使用:

public static int GetMaxSpeed(Car car)
{
    return car.MaxSpeed;
}

在其他情况下,您可以为类型提供方法,并且可以使用嵌套类根据不同的值以不同方式实现方法。为“base”类提供私有构造函数和抽象方法,然后将派生类创建为嵌套类,以便它们仍然可以使用私有构造函数并公开特定值。我将这些类型称为“智能枚举”。

如果要将每个值映射到另一个值,请使用Dictionary<Car,string>(或其他)。如果要将每个值映射到某个操作,请使用Dictionary<Car, Action>

基本上你不会能够使用开关,除非你有一个枚举或某种整体类型......而这通常会很痛苦。使用字典通常是一种更简单的方法。

如果你能提供一个不那么容易解决的更现实的例子,我们可以帮助更多...

答案 1 :(得分:4)

要直接回答您的问题,请将ModelType设为枚举并关闭该值。在下面的示例中,Car类型具有名为“Model”的ModelType属性。

public enum ModelType
{
    Ferrari = 0,
    AstonMartin = 1
}

public int GetMaxSpeed( Car car )
{
    switch( car.Model )
    {
        case Ferrari:
           return 300;
        case AstonMartin:
           return 250;
        default:
           return 100;
    }
}

但更好的问题是,你为什么不使用多态?您可以将Car设为基本类型,并从中继承不同的模型。基本Car类型应具有MaxSpeed属性。无论您从Car继承哪个子类,都可以引用MaxSpeed来获取该特定模型的属性值。这可能会使您的示例(作业?)过于复杂,但它会使您的代码更加OOP。

public class Car
{
    private int _maxSpeed = 200;
    public int MaxSpeed
    {
        get { return _maxSpeed; }
        protected set { _maxSpeed = value; }
    }
}

public class Ferrari : Car
{
    public Ferrari()
    {
        // Constructor 
        this.MaxSpeed = 250;
    }
}

// client code
public void DoStuff()
{
   Car ferrari = new Ferrari();
   Console.WriteLine( ferrari.MaxSpeed );
}

如果你想拥有一个包含汽车列表的车库类,它将类似于以下内容。请记住,这是非常粗略的代码,但它会在评论中向您显示我正在谈论的内容。

public class Garage
{
    private List<Car> Cars { get; set; }

    public Garage()
    {
       this.LoadCars();
    }

    private void LoadCars()
    {
       this.Cars = new List<Car>();
       this.Cars.Add( new Ferrari() );
       this.Cars.Add( new AstonMartin() );
    }

    public int GetMaxSpeedOfAllCars()
    {
        int maxSpeed = 0;

        foreach( Car car in this.Cars )
        {
            if( car.MaxSpeed > maxSpeed )
            {
                maxSpeed = car.MaxSpeed;
            }
        }

        return maxSpeed;
    }

}

答案 2 :(得分:0)

您将无法执行此操作,因为C#仅支持切换案例的编译时常量。相反,你应该使用if / else块。

答案 3 :(得分:0)

我会仅仅根据一般原则,创建这些实例的字典(或只是维护一个List),而不是打开它们。切换语句有时是必要的,但它们很少是“SOLID”代码;无论何时创建新类型的Car,您都必须更改switch语句来处理这种新案例。

static void Main(string[] args)
{
    Console.WriteLine(GetMaxSpeed(Car.Ferarri));
    Console.ReadLine();
}

public static int GetMaxSpeed(string ModelType)
{
    foreach(var car in Car.Cars)
       if(car.Name == ModelType)
          return car.MaxSpeed;
}

public enum Car
{
    public int MinSpeed;
    public int MaxSpeed;
    public string Name;

    public Car(string Name, int MinSpeed, int MaxSpeed)
    {
        this.Name = Name;
        this.MinSpeed = MinSpeed;
        this.MaxSpeed = MaxSpeed;
    }

    public static List<Car> Cars = new List<Car>
    {
       new Car(Car.Ferrari, 30, 240);
       new Car(Car.VW, 10, 50);
       new Car(Car.AstonMartin, 75, 180);        
    }

    public static const string Ferrari = "Ferrari";
    public static const string VW = "VW";
    public static const string AstonMartin= "AstonMartin";
}

如果您只需要打开对象引用,请尝试启用唯一标识该汽车的专用整数类型字段; ID字段。然后,您可以比较switch语句中的ID而不是引用。

static void Main(string[] args)
{
    Console.WriteLine(GetMaxSpeed(Car.Ferrari));
    Console.ReadLine();
}

public static int GetMaxSpeed(Car ModelType)
{
    switch (ModelType.Id)
    {
        case Car.Ferrari.Id:
            return Car.Ferrari.MaxSpeed;

        case Car.VW.Id:
            return Car.VW.MaxSpeed;

        case Car.AstonMartin.Id:
            return Car.AstonMartin.MaxSpeed;
    }
}

public class Car
{
    public int MinSpeed;
    public int MaxSpeed;
    internal int Id;

    public Car(int MinSpeed, int MaxSpeed)
    {
        this.MinSpeed = MinSpeed;
        this.MaxSpeed = MaxSpeed;
    }

    public static Car Ferrari = new Car(30, 240){Id = 1};
    public static Car VW = new Car(10, 50){Id = 2};
    public static Car AstonMartin = new Car(75, 180){Id = 3};
}

答案 4 :(得分:0)

从C#7.0开始,您可以使用模式匹配:

       public static void RepairCar(Car BrokenCar)
    {
        switch (BrokenCar)
        {
            case { } car when car == Car.Ferrari:
                Console.WriteLine("${0} of Insurance Needed", CalculateInsurance(BrokenCar));
                // 
                // Repair Algorithm Here
                //
                break;

            case { } car when car == Car.BMW:
                System.Console.WriteLine("${0} of Insurance Needed", CalculateInsurance(BrokenCar));
                // 
                // Repair Algorithm Here
                //
                break;

            case { } car when car == Car.Audi:
                Console.WriteLine("${0} of Insurance Needed", CalculateInsurance(BrokenCar));
                // 
                // Repair Algorithm Here
                //
                break;

            default:
                Console.WriteLine("${0} of Insurance Needed", CalculateInsurance(BrokenCar));
                // 
                // Repair Algorithm Here
                //
                break;
        }
    }