c# - 将父类动态转换为多个子类之一

标签 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、else if、else if、else if 语句。

最佳答案

在您的基类中将一个方法声明为virtualabstract,您可以在派生类中使用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/

相关文章:

c# - 如何在存储库中的域模型上设置私有(private)字段

c# - 静态方法中的变量共享

c# - 为什么我的 ASP.NET 部署服务器不使用配置的环境名称?

c# - 模拟C#中同一类中的方法

c# - 使用具有相同结构的两个不同表

c# - 添加用于填充字符串的参数 (C#)

c# - 如何检索所有 RAS 连接?

C# 标记结构性能

c# - 在 Fluent Migrator 中回滚到以前的版本

c# - 在 WinForms 中托管 IE 8 并打开 PDF