【问题标题】:Some trouble with subclass constructor子类构造函数的一些问题
【发布时间】:2012-09-04 12:23:13
【问题描述】:

假设我有这个例子:

class A : SomeAbstractClassWithProperties
{
  public A(string id, int size)
  {
    this.Name = "Name1";
    this.Something = new SomethingElse(id, size);
  }

  //...some stuff
}

class B : A
{
  public B(string id, int size)
  {
    this.Name = "Name2";
    this.Something = new SomethingElse(id, size);
  }
}

好吧,这行不通:

Inconsistent accessibility: base class A is less accessible than class 'B'
'A' does not contain a constructor that takes 0 arguments

但是正如我们所见,Class AClass B 的构造函数几乎相同。只是 this.Name 不同。我如何重写B 类?有什么建议?谢谢你

【问题讨论】:

  • 每个人都发布了复制无效构造函数声明public CLASS B(string id, int size){/*stuff*/}的答案,这有点有趣:)

标签: c# .net inheritance constructor


【解决方案1】:

请更新您的代码

class B : A
{
  public class B(string id, int size) : base(id, size) 
  { 
     this.Name = "Name2";
  }
}

情况是你 B 构造函数试图调用不存在的 A() 默认构造函数。

【讨论】:

    【解决方案2】:

    你应该像这样向A类添加默认(不带参数)构造函数或修改B类的构造函数

    public class B(string id, int size) : base(id, size)
      {
        this.Name = "Name2";
        this.Something = new SomethingElse(id, size);
      }
    

    【讨论】:

    • 我真的需要添加 this.Something = new SomethingElse(id, size);再来一次?
    【解决方案3】:

    当您创建 B 的实例时,由于 B 从 A 扩展,因此您也将调用 A 的构造函数。 由于您正在为 A 类定义一个构造函数,因此您不再拥有默认的无参数构造函数,因此您必须在 B 构造函数中调用 A 的构造函数并传递所需的参数。

    public A(string id,int size):base(param1,param2...paramX)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多