C#覆盖泛型类型的抽象方法

时间:2014-09-11 06:09:23

标签: c# generics methods override abstract

我做了很多搜索,我认为我的模式正确但它仍然没有编译,我真的很感激一只手......

我有一个通用类:

public abstract class CTopology<TTopology>
{
    protected abstract TTopology Pcalc();
    public TTopology PLosses()
    { do something
      return this.PCalc()
    }

然后是派生类

   public class CInverter : CTopology<CPBoost>
    { 
     protected override CPInv PCalc()
        {
         CPInv Calc = new CPInv();
         do something
         return Calc;
        }
     }

现在我收到了这两个编译错误:

错误1'iSine46.CInverter'未实现继承的抽象成员'iSine46.CTopology.Pcalc()'

错误2'Iceine46.CInverter.PCalc()':找不到合适的方法来覆盖

4 个答案:

答案 0 :(得分:4)

您的override-method与基类提供的结果类型不同。您需要返回CPBoost实例:

public class CInverter : CTopology<CPBoost> { 
    protected override CPBoost PCalc() { ... }
    ...
}

答案 1 :(得分:1)

错误的原因是您应该保留方法的签名

public abstract class CTopology<TTopology> {
  // Returns TTopology
  protected abstract TTopology Pcalc();
  ...
}

public class CInverter : CTopology<CPBoost> { 
  // Should also return TTopology, that is CPBoost in the case and not CPInv!
  protected override CPBoost PCalc() {
    ...
  }
  ...
}

答案 2 :(得分:1)

public abstract class CTopology<TTopology>
{
  protected abstract TTopology Pcalc();
}


public class CInverter : CTopology<CPBoost>
{ 
  // note that the return type is of the type you chose for TTopology
  // and the capitalization is correct
  protected override CPBoost Pcalc() 
  {
     return something;
  }
}

答案 3 :(得分:0)

public class CInverter : CTopology<CPBoost> { 
// You should return TTopology instead of CPInv
    protected override CPBoost PCalc() {
    ....
    }

}