所以我对编程还很陌生,我试图看看是否有可能编写一个方法来检查父类以找到它的类型,然后为任一结果执行相同的代码块。基本上,我只是想看看是否有办法在有多个不同的子类时避免 long if,else if 语句。
例如,而不是
public Class Shape
public Class Circle : Shape
public Class Rectangle : Shape
public Class Polygon : Shape
....
Shape shape;
if(shape.GetType() == typeof(Rectangle))
{
var asRectangle = (Rectangle)shape;
doSomething();
}
else if (shape.GetType() == typeof(Circle))
{
var asCircle = (Circle)shape;
doSameSomething();
}
else if (shape.GetType() == typeof(Polygon))
{
var asPoly = (Polygon)shape;
doSame();
}
执行以下操作:
if (shape.GetType() == typeof(Rectangle)) var someShape = (Rectangle)shape;
else if (shape.GetType() == typeof(Circle)) var someShape = (Circle)shape;
else if (shape.GetType() == typeof(Polygon)) var someShape = (Polygon)shape;
method(someShape)
{
doStuff...
}
我知道你不能像上面那样声明 var ,你也不能这样做:
var dd;
if(something) var = whatever;
但是我想知道是否有任何方法可以重用该方法而不必每次我需要对形状做某事时都编写 if、else if、else if、else if 语句。