所以我对编程还很陌生,我想看看是否可以编写一种方法来检查父类的类型,然后为任一结果执行相同的代码块。基本上,我只是想看看是否有一种方法可以在有多个不同的子类时避免长 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 语句。
最佳答案
在您的基类中将一个方法声明为virtual
或abstract
,您可以在派生类中使用override 关键字再次声明它。这允许您将对象视为 Shape
并调用一个通用函数,但让它根据实例实际属于哪个类调用适当的方法。
public abstract class Shape
{
public abstract void SayMyName();
}
public class Circle : Shape
{
public override void SayMyName()
{
Console.WriteLine("I'm a circle!");
}
}
public class Rectangle : Shape
{
public override void SayMyName()
{
Console.WriteLine("I'm a rectangle!");
}
}
public class Polygon : Shape
{
public override void SayMyName()
{
Console.WriteLine("I'm a polygon!");
}
}
然后你可以这样消费它:
List<Shape> shapes = new List<Shape>(new Shape[]
{
new Circle(),
new Rectangle(),
new Polygon(),
});
foreach (Shape s in shapes)
s.SayMyName();
关于c# - 将父类动态转换为多个子类之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19324725/