C#继承和重写时在对象声明中新增

C#继承和重写时在对象声明中新增,c#,inheritance,polymorphism,new-operator,overriding,C#,Inheritance,Polymorphism,New Operator,Overriding,比如说, 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(

比如说,

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()”是什么意思?“new Bar()”不是仅仅意味着分配内存吗?

new Bar()
意味着创建一个新的
Bar
对象并调用默认构造函数(在这种情况下它不做任何操作)

它返回
true
,因为
test.DoSomething()
返回
true
,因为它对
Foo
实现有一个覆盖(因此不会调用
Foo
实现)。

新建条()
意味着创建一个新的
Bar
对象并调用默认构造函数(在这种情况下,它不起任何作用)

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

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

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

新Bar()
实际上创建了一个Bar类型的新对象

<> > <代码>虚拟> /代码> />代码>覆盖> <代码>和<代码>新< /代码>(在方法重写的上下文中)是您是否希望编译器在确定要执行哪种方法时考虑<强>引用<>强>类型或<强>对象< /强>的类型。< /P> 在本例中,您有一个名为
test
的类型为“reference to Foo”的引用,该变量引用一个类型为Bar的对象。因为
DoSomething()
是虚拟的并被重写,这意味着它将调用Bar的实现,而不是Foo的实现

除非您使用虚/重写,否则C#只考虑引用的类型。也就是说,任何类型为“reference to Foo”的变量都将调用Foo.DoSomething(),而任何“reference to Bar”都将调用Bar.DoSomething(),无论引用的对象实际是什么类型。

new Bar()
实际上创建了一个Bar类型的新对象

<> > <代码>虚拟> /代码> />代码>覆盖> <代码>和<代码>新< /代码>(在方法重写的上下文中)是您是否希望编译器在确定要执行哪种方法时考虑<强>引用<>强>类型或<强>对象< /强>的类型。< /P> 在本例中,您有一个名为
test
的类型为“reference to Foo”的引用,该变量引用一个类型为Bar的对象。因为
DoSomething()
是虚拟的并被重写,这意味着它将调用Bar的实现,而不是Foo的实现


除非使用virtual/override,否则C#只考虑引用的类型。也就是说,任何类型为“reference to Foo”的变量都将调用Foo.DoSomething(),任何“reference to Bar”都将调用Bar.DoSomething()无论被引用的对象实际上是什么类型。

为什么您希望它为false?重写该方法的意义是什么?也许您感兴趣?我认为“Foo-test”的可能副本是创建一个Foo类型的对象测试,尽管“new Bar()”设置。我不知道是否有更好的解释来解释内存分配和对象创建。这对我来说会更清楚。为什么你会认为它是错误的?重写该方法的意义是什么?也许你感兴趣?可能是我在想的“Foo test”的重复是创建一个Foo类型的对象测试,尽管设置了“new Bar()”。我不知道是否有更好的解释来解释内存分配和对象创建。这对我来说会更清楚。
Foo test = new Bar();