【问题标题】:Inheriting from a class that inherits from a abstract class从继承自抽象类的类继承
【发布时间】:2009-11-20 04:18:54
【问题描述】:

我试图继承一个类 Blah2,但在添加一个方法后它说 BlahA 没有实现该方法。

如何向我的新类添加方法?

public class Blah2 : BlahA
{

}

public class Blah3 : Blah2
{
    public List<int> MyNewMethod()
    {

    }
}

注意:BlahA 是一个抽象类。

更新

public abstract class BlahA : IBlah
{

}

更新 II - 错误

Error   3   'Blah.Components.BlahA' does not contain a definition for 'Blah3' and no extension method 'Blah3' accepting a first argument of type 'Blah.Components.BlahA' could be found (are you missing a using directive or an assembly reference?)   

【问题讨论】:

  • 什么方法没有实现? BlahA 看起来像什么?它是否声明了任何抽象方法?
  • 您提供的代码不够用。那应该行得通。如果可能,列出更多代码以及您遇到的错误。
  • BlahA 看起来像什么?您是否已将 BlahA 声明为抽象?
  • BlahA 是否实现接口?
  • 请提供 BlahA 的定义,否则我们只是在黑暗中冒险。谢谢!

标签: c# oop


【解决方案1】:

如果它实现了您在 cmets 中发布的接口,那么问题是您的 BlahA 类不满足接口的要求。接口中一定有一些方法(我假设它是 MyNewMethod)你没有在你的抽象 BlahA 类中实现。

如果我的假设是正确的,请将其添加到您的基类中:

public abstract List&lt;int&gt; MyNewMethod();

并在您的子类中,将单词 override 添加到您的方法声明中。

一些代码:

 public interface MyInterface
    {
        void MyMethod();
    }

    public abstract class Base : MyInterface
    {
        public abstract void MyMethod();
    }

    public class SubA : Base 
    {
        public override void MyMethod()
        {
            throw new NotImplementedException();
        }
    }

    public class SubB : SubA
    {
        public void Foo() { }
    }

【讨论】:

    【解决方案2】:

    编写此代码并编译工作正常

    public abstract class BlahA
        {
        }
    
        public class Blah2 : BlahA
        {
        }
    
        public class Blah3 : Blah2
        {
            public List<int> MyList()
            {
                return new List<int>();
            }
        }
    

    我们需要更多不工作的代码

    编辑:

    从 cmets 你需要从抽象类的接口中实现方法。

    public interface IBlah
        {
            int GetVal();
        }
    
        public abstract class BlahA : IBlah
        {
            public int GetVal()
            {
                return 1;
            }
    
        }
    
        public class Blah2 : BlahA
        {
        }
    
        public class Blah3 : Blah2
        {
            public List<int> MyList()
            {
                int i = GetVal();
                return new List<int>();
            }
        }
    

    【讨论】:

    • 如果他不想在抽象类中实现接口方法,他也不必。他可以将其声明为抽象的。请参阅我的代码示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 2021-10-24
    • 1970-01-01
    相关资源
    最近更新 更多