简体   繁体   中英

C# new in object declaration when inherit and override

For example,

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());
    }
}

Why is the answer True? What does "new Bar()" mean? Doesn't "new Bar()" just mean allocate the memory?

new Bar() actually makes a new object of type Bar.

The difference between virtual / override and new (in the context of a method override) is whether you want the compiler to consider the type of the reference or the type of the object in determining which method to execute.

In this case, you have a reference of type "reference to Foo" named test , and this variable references an object of type Bar. Because DoSomething() is virtual and overridden, this means it will call Bar's implementation and not Foo's.

Unless you use virtual/override, C# only considers the type of the reference. That is, any variable of type "reference to Foo" would call Foo.DoSomething() and any "reference to Bar" would call Bar.DoSomething() no matter what type the objects being referenced actually were.

new Bar() means create a new Bar object and call the default constructor (which does nothing in this case).

It returns true because test.DoSomething() returns true , as it has an override for Foo implementation (so the Foo implementation will not be called).

Foo test = new Bar();

test is referring to a new object of Bar , hence the call test.DoSomething() calls the DoSomething() of the object Bar . This returns true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM