如何在C#中使用不同方法名称访问父类中的子类方法
问题描述:
我想使用不同的方法名访问基类中的子类方法,试图将子类对象的ref分配给基类,但它显示错误。如何在C#中使用不同方法名称访问父类中的子类方法
以下是我的示例代码:
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();
显示了一个错误。
答
Parent par = new children();
创建新实例children
,但将其分配给Parent
变量。变量类型确定您可以访问的方法和属性。 Parent
没有方法displayChild()
,因此您收到错误消息。
答
当你创建一个Parent
对象到一个新children
例如,你可以投它children
然后使用displayChild
方法。
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();
}
}