c# - 继承如何取代switch case?

标签 c#

我正在使用 C# Switch case 我如何使用继承来替换。 案例就像 1,2,3,4 所以 我该如何实现。

例如:

    public Blocks(int code)
    {
         bool[,] shp1;

        switch (code)
        {
            case 1:
                this._Width = 4;
                this._Height = 1;
                this._Top = 0;
                this._Left = 4;

                shp1 = new bool[_Width, _Height];
                shp1[0, 0] = true;
                shp1[1, 0] = true;
                shp1[2, 0] = true;
                shp1[3, 0] = true;
                this.Shape = shp1;
                break;

            case 2:
                this._Width = 2;
                this._Height = 2;
                this._Top = 0;
                this._Left = 4;

                shp1 = new bool[_Width, _Height];
                shp1[0, 0] = true;
                shp1[0, 1] = true;
                shp1[1, 0] = true;
                shp1[1, 1] = true;
                this.Shape = shp1;
                break;


            default:
                throw new ArgumentException("Invalid Block Code");
        }
    }

最佳答案

基本思想是,您拥有不同类型的对象,不同类型的对象具有相同方法的不同实现,可以为该类型的对象做正确的事情,而不是使用一个方法来决定要做什么。

假设您现在有一个 Car 类,值 (1, 2, 3, ...) 指的是各种刹车配置。在您当前的 Brake() 方法中,您的代码如下所示:

public class Car
{
    public void Brake()
    {
          switch (this.BrakeType)
          {
              case 1:  // antilock brakes
                ....
              case 2:  // 4-wheel disc brakes, no antilock
                ....
              case 3:  // rear-drum, front-disc brakes
                ....

          }
     }
}

您真正想要做的是使用不同的类来实现 Brake 方法。在这种情况下,我将为每种制动器类型设置一个 BrakeStrategy。为汽车对象的配置分配正确的 BrakeStrategy,然后简单地从 Brake 方法调用策略方法。

public class Car
{
     public BrakeStrategy BrakeStrategy { get; set; }

     public void Brake()
     {
         this.BrakeStrategy.Brake();
     }
}

public class ABSBrakes : BrakeStrategy
{
     public void Brake()
     {
        ... do antilock braking...
     }
}

var car = new Car { BrakeStrategy = new ABSBrakes(), ... };
car.Brake();  // does ABS braking

关于c# - 继承如何取代switch case?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1404882/

相关文章:

c# - 秒表(System.Diagnostics)和 System.Timers

c# - 并发执行异步方法

c# - 检测阈值区域

c# - 在 C# 中包私有(private)?

c# - 如何使用 c#.net 将基类的实例复制到派生类基

c# - 使用反射从类列表的属性中获取值

C#:可选方法

c# - 递归函数调用抛出 StackOverFlowException

c# - HttpContext.Current 和 ProcessRequest(HttpContext context) 是否相等?

c# - 使用范围服务的 Hotchocolate 日志记录错误