简体   繁体   中英

How to access child class method in Parent class with different method name in C#

I want to access child class method in base class with different method name,am try to do with assigning ref of child class object to base class,but it shows error.

following is my sample code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Concepts
{
    class Parent 
    {
        public void display()
        {
            Console.WriteLine("I am in parent class");
        }
    }

    class children : Parent
    {
        public void displayChild()
        {
            Console.WriteLine("I am in child class");
        }
    }

    class Program 
    {
        static void Main(string[] args)
        {
            children child = new children();
            Parent par = new children();
            par.displayChild();
            child.display();
            child.displayChild();
            Console.ReadLine();
        }
    }
}

In above code par.displayChild(); shows an error.

Parent par = new children(); creates new instance of children , but assign it to Parent variable. The variable type determines the methods and properties you can access. Parent doesn't have the method displayChild() so you are getting an error.

As you create a Parent object with a new children instance you could cast it to children then use displayChild method.

class Program 
{
    static void Main(string[] args)
    {
        children child = new children();
        Parent par = new children();
        (par as children).displayChild();
        child.display();
        child.displayChild();
        Console.ReadLine();
    }
}

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