继承自继承自抽象类的类

时间:2009-11-20 04:18:54

标签: c# oop

我试图继承一个类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?)   

2 个答案:

答案 0 :(得分:3)

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

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

public abstract List<int> 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() { }
    }

答案 1 :(得分:2)

Wrting此代码和编译工作正常

public abstract class BlahA
    {
    }

    public class Blah2 : BlahA
    {
    }

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

我们需要一些不起作用的代码

编辑:

您需要从抽象类中的接口实现该方法的注释。

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