How to change the reference of a base object to Derived, which was set as a derived type

Why can't I access the M3 method from Derived? Intellisense only shows M1 and M2 from the base class. How can I change the bc link from the base type to the Refernce Type so that I can access the M3 method.

class Program
{
    static void Main(string[] args)
    {
        Base bc = new Derived();
        bc.M3():// error
    }
}

class Base
{
    public void M1()
    {
        Console.WriteLine("M1 from BASE.");
    }
    public void M2()
    {
        Console.WriteLine("M2 from BASE.");
    }
}

class Derived : Base
{
    public void M3()
    {
        Console.WriteLine("M3 from DERIVED.");
    }
}
+4
source share
5 answers

The compiler must resolve the name M3at compile time. This invokes a type reference Base, but Basedoes not have a member of that name. The fact that it points to an instance Derivedat runtime is irrelevant here because the compiler is looking at information available at compile time.

, , bc Derived, . , #. .

+6

, , Base.

Derived bc = new Derived();
bc.M3():// CORRECT

var bc = new Derived();
bc.M3():// CORRECT

Base M3(), Base class

+1

, bc, , Base -, Base.

, :

Base bc = new Derived();
if(DateTime.DayOfWeek == DayOfWeek.Sunday)
{
  bc = new Base();
}
bc.M3();

, bc .

: .

, , , Derived, Base.

Base bc = new Derived();
if(bc is Derived)
{
  ((Derived)bc).M3();
}

- M3

class Base
{
   // Other stuff...

   public virtual void M3()
   {
   }
}

class Derived : Base
{
    public override void M3()
    {
        Console.WriteLine("M3 from DERIVED.");
    }
}
+1

, bc Base.

    Base bc = new Derived();
    ((Derived)bc).M3()

, bc Base Derived.

+1

, , Base.

:

Base bc = null;

if (SomeValue)
{
    bc = new Base();
}
else
{
   bc = new Derived();
}

SomeValue . , bc . . , , .

:

Derived dc = bc as Derived;

if ( dc != null ) // cast succeeded so we have a Derived
{
    dc.M3();
}

, , is: if (dc is Derived).

, , . , , . , - S OLID-.

+1
source

Source: https://habr.com/ru/post/1525754/


All Articles