【问题标题】:C# class inheritance doesn't workC# 类继承不起作用
【发布时间】:2015-01-07 07:37:38
【问题描述】:
namespace MyProgram
{
    public class ParentClass
    {


    }

    public class childClass : ParentClass
    {
        public int Normal()
        {
            return 1;
        }
    }

}

其他地方:

ParentClass parentc = new ParentClass();

parentc.Normal(); //<-- I can't call the function normal!

我需要帮助才能使用它。

【问题讨论】:

  • 是的,因为您制作的是ParentClass,而不是childClass
  • 不能从父类调用子类方法。但是可以从子类调用父类方法。 @PiDEV
  • 我对此投了反对票,因为它没有显示 OP 在研究至少最基本的继承方面付出了任何努力。

标签: c# class inheritance


【解决方案1】:

Parent 没有方法Normal,所以不能调用。按照基本逻辑,父级不会继承其子级的方法;反之亦然。

【讨论】:

    【解决方案2】:

    将普通方法移至父类:

    public class ParentClass
    {
        public int Normal()
        {
            return 1;
        }
    }
    
    public class childClass : ParentClass
    {
    } 
    

    【讨论】:

      【解决方案3】:

      您必须创建子类的引用才能访问 Normal();功能。

      childClass obj=new childClass();
      obj.Normal();
      

      【讨论】:

        【解决方案4】:

        试试这样的;

            class ParentClass
               {
                  public int Normal()
                  {
                    return 1;
                  }
               }
            // Derived class
               class ChildClass: ParentClass
               {
                  public int someMethod()
                  { 
                     return Normal();         
                  }
               }
        

        【讨论】:

          【解决方案5】:

          您需要向下投射对象。 当您需要将子函数应用于父对象时,您可以这样做。 为此,您需要在创建父对象时声明稍后使用子构造函数来转换对象,如下所示:

          class foo{}
          class goo:foo{ public void DoStuff(){} }
          /*.... In the main program ..... */
          foo a = new goo(); // Declaring the a, which is of type foo, might be used as a goo later on.
          

          为了使用,把它扔下来。

          ((goo)a).DoStuff();
          

          希望对你有帮助:)

          【讨论】:

            【解决方案6】:

            您不能从父类调用子类方法。但可以从子类调用父类方法。

            namespace MyProgram
            {
                public class ParentClass
                {
                    public int Normal()
                    {
                        return 1;
                    }
                }
            
                public class childClass : ParentClass
                {
                    Normal(); // which calls the method in Base class(ParentClass)
                    //base.Normal(); //or this one in which base tells that the method is in base class
                } 
            }
            

            【讨论】:

              猜你喜欢
              • 2013-04-24
              • 2015-11-29
              • 1970-01-01
              • 1970-01-01
              • 2016-10-01
              • 1970-01-01
              • 1970-01-01
              • 2018-05-24
              • 2015-03-04
              相关资源
              最近更新 更多