+-
c#-将父类动态转换为多个子类之一
因此,我对编程还不陌生,因此我试图查看是否有可能编写一种方法来检查父类的类型以找到其类型,然后针对任何结果执行相同的代码块.基本上,我只是想看看是否有一种方法可以避免在有多个不同的子类时避免长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,if,if,if,if,if语句的方法.

最佳答案
在基类中将一个方法声明为虚拟方法或抽象方法,然后可以使用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#-将父类动态转换为多个子类之一 - 乐贴网