使用子类的C#类未实现继承的抽象成员错误 [英] C# class using subclass does not implement inherited abstract member error

查看:531
本文介绍了使用子类的C#类未实现继承的抽象成员错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要编译的C#代码 非常简单,从testDMOBase继承的testDMO 然后测试从testBase继承的

Here's the c# code I'm trying to compile Fairly simple, testDMO that inherits from testDMOBase Then test that inherits from 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)':不适合 发现要覆盖的方法

'test' does not implement inherited abstract member 'testBase.LoadCRUD(testDMOBase)' 'test.LoadCRUD(testDMO)': no suitable method found to override

在重写方法上不能使用子类吗?

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

推荐答案

在重写方法上不能使用子类吗?

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

不.除了别的以外,如果调用者提供的实例不是您的子类 other ,您还希望调用哪种实现?

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?

您可能会争辩说,能够使用更通用的子类方法(例如,使用参数 superclass 来覆盖基本方法) >原始参数类型,或者返回类型是原始返回类型的子类),但是.NET仍然不允许任何一种.覆盖方法的参数和返回类型必须至少与通用类型参数替换之后完全匹配原始方法 .

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

请注意,即使在示例代码中,也应遵循.NET命名约定.

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

这篇关于使用子类的C#类未实现继承的抽象成员错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆