2014-09-11 55 views
0

我也颇有几分搜索的,我以为我听错了图案右侧的抽象方法,但它仍然没有编制,我真的很感激手...C#覆盖通用型

我有一个泛型类:

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

现在,我得到这2编译错误:

错误1 'iSine46.CInverter' 不实现继承的抽象构件 'iSine46.CTopology.Pcalc()'

错误2 'iSine46.CInverter.PCalc()':发现重写没有合适的方法

+0

Visual Studio中有智能感知功能与此帮助。在派生类中,输入“override PCalc”并按回车。 Visual Studio将使用正确的修饰符来放入正确的方法或属性。 – Grax 2014-09-11 18:02:03

回答

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() { 
    ... 
    } 
    ... 
} 
+0

我曾试过,但我得到这个错误,而不是: 错误无法找到类型或命名空间名称'TTopology'(你是否缺少using指令或程序集引用?) – ag101 2014-09-11 06:17:08

4

您的覆盖法没有为你的基类提供的相同结果类型。您需要返回CPBoost实例:

public class CInverter : CTopology<CPBoost> { 
    protected override CPBoost PCalc() { ... } 
    ... 
} 
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; 
    } 
} 
0
public class CInverter : CTopology<CPBoost> { 
// You should return TTopology instead of CPInv 
    protected override CPBoost PCalc() { 
    .... 
    } 

}