如何在c#中将一个抽象类放在另一个抽象类中?

时间:2013-09-02 08:03:10

标签: c# inheritance abstract-class

这实际上是一个设计问题 假设我有一个接口 a 和一个类 aa ,抽象方法 m1 m2 ,它继承自

public interface a
{
  string m1();
  string m2();
}

public abstract class aa:a
{
  public abstract string m1();
  public abstract string m2();
}  

我还有一个不同的界面 b 和一个继承自它的 bb 类。

public interface b
{
  string n1();
  string n2();
}

public abstract class bb:b
{
  public abstract string n1();
  public abstract string n2();
}  

我想强制继承 aa 的类来实现类 bb 的方法(同样必须实现 m1 m2

这样做的正确方法是什么?

public abstract class aa:a
{
  public abstract string m1();
  public abstract string m2();
  public abstract bb()?? 
  or public abstract bb.n1()???
}

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作之一:从bb类继承 aa; 在一个类中实现 b接口; 中实现 b接口

// Inherit aa from bb class
public abstract class aa:a, bb {
  public abstract string m1();
  public abstract string m2();

  // public abstract string n1(); // <- From bb class
  // public abstract string n2(); // <- From bb class
}

// Implement b interface in aa class
public abstract class aa:a, b {
  public abstract string m1();
  public abstract string m2();

  public abstract string n1(); // <- From b interface
  public abstract string n2(); // <- From b interface
}

// Implement b interface in aa class explicitly
public abstract class aa:a, b {
  public abstract string m1();
  public abstract string m2();

  protected abstract string core_n1(); // <- Put (override) b interface implementation here
  protected abstract string core_n2(); // <- Put (override) b interface implementation here

  // Can't be abstract itself but can call an abstract method
  b.string n1() { // <- explicit implementation, mo public or other modifier here!
    return core_n1();
  }
  // Can't be abstract itself but can call an abstract method
  b.string n2() { // <- explicit implementation, mo public or other modifier here!
    return core_n2();
  }
}