C#创建实例案例

Cases of creating instance in C#

我刚刚学习了C#中的继承和多态性,我对这三种情况感到困惑。当我们有一个基础和派生 class.

时,您可以创建一个实例

能否请您解释一下差异(尤其是 Obj1 和 Obj2)?

class Program
{
    static void Main()
    {
        Shape     obj1 = new Shape();
        Shape     obj2 = new Rectangle();
        Rectangle obj3 = new Rectangle();

    }
}

class Shape
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

class Rectangle : Shape
{
    public string Property3 { get; set; }
}
Shape obj1 = new Shape();

obj1 是一个形状。它有 Property1 和 Property2。它没有 Property3。

Shape obj2 = new Rectangle();

obj2 是一个 Rectangle,在您实例化它的那一刻被向下转化为 Shape。如果 Rectangle 覆盖任何 Shape 行为(在您的示例中没有),那么将在运行时调用 Rectangle 行为,而不是基础 Shape 的行为class。它有一个可以在其内部使用的 Property3,但您不能通过此方法访问它,因为它已经向下转换为 Shape.

Rectangle obj3 = new Rectangle();

obj3 是 Rectangle。您可以通过此方法访问 Property3。您可以将它传递给任何需要 Shape 的方法,因为 RectangleShape.

我建议您按照这些思路编写更多代码,并在一个简单的控制台应用程序中对其进行调试,以查看在不同情况下会发生什么情况。就个人而言,我发现边做边学是最好的方法。