C# 如何在C中使用不同的方法名访问父类中的子类方法#

C# 如何在C中使用不同的方法名访问父类中的子类方法#,c#,C#,我想用不同的方法名访问基类中的子类方法,我试图将子类对象的ref赋值给基类,但它显示了错误 以下是我的示例代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Concepts { class Parent { public void display()

我想用不同的方法名访问基类中的子类方法,我试图将子类对象的ref赋值给基类,但它显示了错误

以下是我的示例代码:

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

在上面的代码
par.displayChild()中显示错误。

父项par=新子项()创建子项的新实例,但将其分配给父项变量。变量类型决定了可以访问的方法和属性
Parent
没有方法
displayChild()
,因此您得到了一个错误。

当您使用新的
children
实例创建
Parent
对象时,您可以将其强制转换为
children
方法

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