【问题标题】:C# Error from derived class [duplicate]来自派生类的 C# 错误 [重复]
【发布时间】:2023-04-05 05:51:01
【问题描述】:

我有一个基类:

public class Base {
  public string Foo { get; set; }
  public float Bar { get; set; }
  public float Foobar { get; set; }

  public Base (string foo, float bar, float foobar) {
      Foo = foo;
      Bar = bar;
      Foobar = foobar;
  }
}

当我尝试添加扩展它的类时出现错误:

public class Derived : Base {
    public Base derived = new Derived ("Foo", 0f, 0f);
}

收到的错误说明如下:Base does not contain a constructor that takes 0 arguments

我在 Derived 类的第 1 行收到此错误。 发生这种情况的任何修复/原因?

【问题讨论】:

  • 构造函数不会被继承。在Derived 中声明一个构造函数,它接受相同的参数并使用语法public Derived(...) : base(...) 调用基本构造函数。

标签: c# unity5


【解决方案1】:

由于Base类的构造函数接受三个参数,你需要从Derived类的构造函数中传递这些参数的值:

public Derived(string foo, float bar, float foobar): base(foo, bar, foobar) {}

【讨论】:

    【解决方案2】:

    在派生类中不定义构造函数,默认为无参数构造函数。基类没有,因此派生类无法实例化其基类(因此也无法实例化自身)。

    在派生类中定义一个使用基类构造函数的构造函数:

    public Derived(string foo, float bar, float foobar) : base(foo, bar, foobar) { }
    

    这只是一个传递构造函数。如果你愿意,你也可以使用无参数的,但你仍然需要使用带有一些值的基类的构造函数。例如:

    public Derived() : base("foo", 1.0, 2.0) { }
    

    它是一个普通的构造函数,和其他任何构造函数一样,可以包含任何你喜欢的逻辑,但它需要调用基类的唯一构造函数并带有一些值。


    注意:这意味着您可能根本不需要这个:

    public Base derived = new Derived ("Foo", 0f, 0f);
    

    您似乎正在尝试将Base 的实例创建为Derived成员。但是Derived Base 的一个实例。如果您想使用 Base 作为这样的实例,那么您将不想使用继承:

    public class Derived {  // not inheriting from Base
        public Base base = new Base ("Foo", 0f, 0f);
    }
    

    当然,此时“基”和“派生”的名称会产生误导,因为这些类实际上并不在继承结构中。

    【讨论】:

      【解决方案3】:

      试试这个:

      public class Derived : Base
      {
          public Derived() 
              : base("Foo", 0f, 0f)
          {
      
          }
      
          public Base derived = new Derived();
      }
      

      你也可以使用对象初始化语法:

      public Base derived = new Derived() { Foo = "Foo", Bar = 0f, Foobar = 0f };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-22
        • 2015-07-13
        • 2010-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多