首页 文章

继承和覆盖时,对象声明中的c#new

提问于
浏览
0

例如,

public class Foo
    {
        public virtual bool DoSomething() { return false; }
    }

    public class Bar : Foo
    {
        public override bool DoSomething() { return true; }
    }

    public class Test
    {
        public static void Main()
        {
            Foo test = new Bar();
            Console.WriteLine(test.DoSomething());
        }
    }

为什么答案是真的? “新酒吧()”是什么意思? “new Bar()”是不是意味着分配内存?

3 回答

  • 0

    new Bar() 实际上是一个Bar类型的新对象 .

    virtual / overridenew (在方法覆盖的上下文中)之间的区别在于您是否希望编译器在确定执行哪种方法时考虑 reference 的类型或 object 的类型 .

    在这种情况下,您具有名为 test 的"reference to Foo"类型的引用,并且此变量引用Bar类型的对象 . 因为 DoSomething() 是虚拟的并且被覆盖,这意味着它将调用Bar 's implementation and not Foo' .

    除非您使用虚拟/覆盖,否则C#仅考虑引用的类型 . 也就是说,任何类型“引用Foo”的变量都会调用Foo.DoSomething(),任何“Bar的引用”都会调用Bar.DoSomething(),无论实际引用的对象是什么类型 .

  • 0
    Foo test = new Bar();
    

    test 指的是 Bar 的新对象,因此调用 test.DoSomething() 调用对象 BarDoSomething() . 这返回true .

  • 5

    new Bar() 表示创建一个新的 Bar 对象并调用默认构造函数(在这种情况下不执行任何操作) .

    它返回 true ,因为 test.DoSomething() 返回 true ,因为它具有 Foo 实现的覆盖(因此不会调用 Foo 实现) .

相关问题