【问题标题】:Child class complains about parent class constructor [duplicate]子类抱怨父类构造函数[重复]
【发布时间】:2021-10-28 08:13:30
【问题描述】:

我有一个基类,它在构造函数中接受一个参数 然后我创建了一个子类,并且还使用了带有 on 参数的构造函数。

想法是DeviceA的构造函数覆盖了GenericDevice的构造函数

但是系统报错

Error   CS7036  There is no argument given that corresponds to the required formal parameter 'address' of 'GenericDevice.GenericDevice(string)' 

不知道为什么会出现这个错误,因为DeviceA不需要GenericDevice的构造函数,它有自己的

class GenericDevice {
    GenericDevice(string address){
    
    }
    void Connect() {
    }
}

class DeviceA : GenericDevice
{
    DeviceA(string address) {

    }
    void Foo() {
    }
}

【问题讨论】:

  • DeviceA(string address) base(address) {...
  • 将你的 DeviceA 构造函数声明更改为:DeviceA(string address) : base(address) { - 必须告诉编译器如何调用基类中的构造函数。
  • 是的,如果要粘贴代码,请粘贴实际代码
  • 是的,这似乎有效,谢谢

标签: c#


【解决方案1】:

像这样修复你的代码:

class GenericDevice
{
    protected GenericDevice(string address)
    {
    }

    void Connect()
    {
    }
}

class DeviceA : GenericDevice
{
    DeviceA(string address) : base(address)
    {
    }

    void Foo()
    {
    }
}

在派生类中,如果未使用 base 关键字显式调用基类构造函数,则隐式调用无参数构造函数(如果有)。 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-constructors

所以你也可以像这样改变你的代码:

class GenericDevice
{
    protected GenericDevice()
    {
    }

    GenericDevice(string address)
    {
    }

    void Connect()
    {
    }
}

class DeviceA : GenericDevice
{
    DeviceA(string address)
    {
    }

    void Foo()
    {
    }
}

【讨论】:

  • 如果构造函数是private(如果没有protectedpublic等类型的修饰符,则只能通过显式: base( ... )或隐式: base(),以防继承类嵌套在基类中。示例:class B { B() { } class C : B { } }
【解决方案2】:
class GenericDevice
{
    public GenericDevice()
    {

    }
    public GenericDevice(string address)
    {

    }
    void Connect()
    {
    }
}

class DeviceA : GenericDevice
{
    public DeviceA(string address) : base(address)
    {
        // calls the GenericDevice(string address) Constructor
    }


    public DeviceA(string address, int number) : base()
    {
        // calls the GenericDevice() Constructor
    }

    void Foo()
    {
    }
}

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 2012-09-15
    • 2016-01-08
    • 2018-02-28
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多