【问题标题】:Unable to inherit constructor, An object reference is required无法继承构造函数,需要对象引用
【发布时间】:2020-07-22 03:31:59
【问题描述】:

考虑:

using System;

namespace TuristickaAgencija
{
    public class World
    {
        protected char[] dest;

        public World(char[] dest)
        {
            this.dest = dest;
        }
    }

    class Client : World
    {
        private char[] name;
        private char[] surname;
        private int age;
        private int noCounter;
        private bool hasVehicle;

        public Client(char[] name, char[] surname, int age, int noCounter, bool hasVehicle) : base(dest)
        {
            this.name = name;
            this.surname = surname;
            this.age = age;
            this.noCounter = noCounter;
            this.hasVehicle = hasVehicle;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

我收到 2 个错误:

非静态字段、方法或属性“World.dest”需要对象引用

“程序”类型的声明缺少部分修饰符

我希望所有类都在同一个文件中。

【问题讨论】:

  • 您必须将dest 作为参数传递给构造函数,即使您将初始化委托给基类。我也可以建议string 而不是char[] 吗?使用起来更容易。
  • base(dest: dest) 喜欢这样吗?
  • 只需将 'char[] dest' 像这样添加到 public Client(char[] name, char[] surname, int age, int noCounter, bool hasVehicle, char[] dest)
  • 我把char[]改成string,出现同样的错误。
  • 你有public Client(char[] name, char[] surname, int age, int noCounter, bool hasVehicle) : base(dest)。在定义 dest 之前,您不能调用 base(dest)。例如,您可以传递base(name),或者您可以将dest 添加到World 构造函数的参数列表中。而且,正如@PatrickRoberts 指出的那样,您真的想了解char[]string 之间的区别(并了解您不希望在这里使用char[]

标签: c# inheritance constructor derived-class


【解决方案1】:

您需要传递一个有效值才能初始化 dest。 dest 尚未在构造函数的 csope 中定义,您正在调用基本 ctor 并且应该初始化它。

您可以传递名称,或确定名称或添加另一个参数并使用它。

至于部分错误,可能您已经在代码的其他地方定义了一个 Program 类,并且您不能声明 2 个具有相同名称的类。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    不清楚dest 你试图传递基类的构造函数是什么。您不能将引用传递给尚未实例化的实例的字段。

    您应该向Client 构造函数添加一个参数并将其传递给基本构造函数:

    public Client(char[] name, char[] surname, int age, int noCounter, bool hasVehicle,
        char[] dest) : base(dest)
    {
        this.name = name;
        this.surname = surname;
        this.age = age;
        this.noCounter = noCounter;
        this.hasVehicle = hasVehicle;
    }
    

    或者您应该传递一些默认值,例如 null 或空数组:

    public Client(char[] name, char[] surname, int age, int noCounter, bool hasVehicle) : base(default)
    

    【讨论】:

      猜你喜欢
      • 2014-12-27
      • 1970-01-01
      • 2022-11-03
      • 2013-06-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多