我使用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");
}
}
Run Code Online (Sandbox Code Playgroud)
基本思想是,不是有一个基于状态决定做什么的方法,而是有不同类型的对象,它们具有相同方法的不同实现,为该类型的对象做正确的事情.
假设您现在有一个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
....
}
}
}
Run Code Online (Sandbox Code Playgroud)
你真正想要做的是有不同的类来实现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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3950 次 |
| 最近记录: |