2017-03-06 35 views
0

我想使用不同的方法名访问基类中的子类方法,试图将子类对象的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();显示了一个错误。

回答

1

Parent par = new children();创建新实例children,但将其分配给Parent变量。变量类型确定您可以访问的方法和属性。 Parent没有方法displayChild(),因此您收到错误消息。

0

当你创建一个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(); 
    } 
} 
相关问题