我正在使用 C# Switch case 如何使用继承来替换。
情况就像 1,2,3,4 所以
我怎样才能实现它。
for eg:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)