2

这是我正在尝试编译的 c# 代码 相当简单,testDMO继承自testDMOBase Then test 继承自 testBase

public abstract class testDMOBase { }
public class testDMO : testDMOBase { }
public abstract class testBase
{
    abstract protected void LoadCRUD(testDMOBase dmo);
}
public class test : testBase
{
    override protected void LoadCRUD(testDMO dmo) { }
}

我收到以下错误:

“test”没有实现继承的抽象成员“testBase.LoadCRUD(testDMOBase)”“test.LoadCRUD(testDMO)”:找不到合适的方法来覆盖

在覆盖方法上不应该使用子类吗?

4

3 回答 3

5

Shouldn't the use of a subclass be ok on the override method?

No. Aside from anything else, which implementation would you expect to be called if the caller provided an instance other than your subclass?

testBase t = new test();
t.LoadCRUD(new SomeOtherDMO()); // What would be called here?

You might well argue that it would make sense to be able to override the base method with a subclass method which is more general (e.g. with a parameter which is a superclass of the original parameter type, or with a return type which is a subclass of the original return type) but .NET doesn't allow either of these anyway. The parameter and return types of the overriding method have to match the original method exactly, at least after generic type parameter substitution.

It sounds like you may want to make your base type generic:

public abstract class TestBase<T> where T : TestDmoBase
{
    public abstract void LoadCrud(T dmo);
}

public class Test : TestBase<TestDmo>
{
    public override void LoadCrud(TestDmo dmo)
    {
        ...
    }
}

Note that you should follow .NET naming conventions, too - even in sample code.

于 2013-01-06T21:28:19.480 回答
4

不,在这种情况下,您必须完全遵循abstract方法的签名,才能提供有效的覆盖。

所以,你必须写:

public class test : testBase
{
    override protected void LoadCRUD(testDMOBase dmo)  //BASE CLASS
    { }
}
于 2013-01-06T21:27:09.937 回答
0

Shouldn't the use of a subclass be ok on the override method?

No, method overrides must use the same parameter types as their original declarations.

于 2013-01-06T21:29:15.860 回答