Virtual method of accessing the parent class from the inheritance of the object of the child class

I would like to know if it is possible to access the underlying virtual method using the class of the inheriting class (which overrides the method).

I know this is not a good practice, but the reason I want to know this is technically possible. I do not follow this practice, just asking out of curiosity.

I saw several similar questions, but I did not receive the answer I am looking for.

Example:

public class Parent
{
    public virtual void Print()
    {
        Console.WriteLine("Print in Parent");
    }
}

public class Child : Parent
{
    public override void Print()
    {
        Console.WriteLine("Print in Child");
    }
}

class Program
{
    static void Main(string[] args)
    {
         Child c = new Child();
         //or Parent child = new Child(); 
         child.Print();  //Calls Child class method
         ((Parent)c).Print(); //Want Parent class method call
    }
}

Please explain downvotes. Any reference to an existing similar question (with a satisfactory answer) to stackoverflow is an acceptable answer. Thank.

+5
source share
4 answers

, , :

static void Main(string[] args)
{
    Child child = new Child();
    Action parentPrint = (Action)Activator.CreateInstance(typeof(Action), child, typeof(Parent).GetMethod("Print").MethodHandle.GetFunctionPointer());

    parentPrint.Invoke();
}
+4

- . . "Print in Child" .

+1

, , , :

public class Parent
{
    public virtual void Print()
    {
        Console.WriteLine("Print in Parent");
    }
}

public class Child : Parent
{
    public override void Print()
    {
        base.Print();
        Console.WriteLine("Print in Child");
    }
}

class Program
{
    static void Main(string[] args)
    {
         Child c = new Child();
         //or Parent child = new Child(); 
         child.Print();  //Calls Child class method
         ((Parent)c).Print(); //Want Parent class method call
    }
}
+1

, . , , . :

public class Child : Parent
{
    public void Print(bool onlyCallFather)
    {
    if(onlyCallFather)
        base.Print();
    else
        Print();
    }
}

:

class Program
{
    static void Main(string[] args)
    {
         Child c = new Child();
         child.Print(false);  //Calls Child class method
         child.Print(true);  //Calls only the one at father
    }
}

That way, it will do what you wanted to do. I really saw this workaround to say if you want the base method to be called or not.

0
source

All Articles