【问题标题】:I don't understand why this constructor does not work我不明白为什么这个构造函数不起作用
【发布时间】:2016-08-15 05:57:13
【问题描述】:

我有一个简单的 FiniteStateMachine,FSM 的状态是从 FSMState 抽象类继承的类,它强制实现某些方法和字段,ownerClass 字段是一个泛型类型,所以每个状态都成立对拥有 FSM 实例的类的引用

public abstract class FSMState<T>
{
    /// <summary>
    /// Reference to the owner class of this State.
    /// </summary>
    protected abstract T ownerClass { get; set; }
    /// <summary>
    /// The ID name of this State.
    /// </summary>
    public abstract string Name { get; set; }

    //Constructor
    public FSMState(T owner, string name)
    {
        ownerClass = owner;
        Name = name;
    }
}

所以状态类看起来像这样

public class MovingState : FSMState<AI>
{
    protected override AI ownerClass { get; set; }

    public override string Name { get; set; }

    //Contructor.
    public MovingState(AI owner, string name)
    {
        ownerClass = owner;
        Name = name;
    }

}

但是构造函数不起作用,我得到了这两个错误

错误 CS7036 没有给出与 FSMState.FSMState(AI, string) 所需的形式参数所有者相对应的参数

错误:类型 FSMState 不包含采用 0 个参数的构造函数

我不知道这样做是否可行,我希望继承 FSMState 形式的类实现一个构造函数,该构造函数设置字段 NameownerClassownerClass 字段必须是通用的

我正在尝试做一些不可能的事情?

【问题讨论】:

  • 一旦你提供了一个构造函数,如果你打算实例化没有参数的对象,你还必须提供一个无参数的构造函数。
  • 另外,您不能强制特定构造函数的实现。 C# 中没有继承构造函数,因此没有“抽象”构造函数的机制。
  • @GeorgeStocker 听起来他打算让对象在没有参数的情况下被实例化。
  • @Servy 他的错误消息显示他正试图在某个地方这样做。没有看到实现代码;我只是根据错误信息猜测。
  • @GeorgeStocker 显式构造函数隐式调用无参数构造函数。它没有找到一个是另一个错误消息的原因(因为没有双参数构造函数)。

标签: c# generics inheritance constructor abstract-class


【解决方案1】:

需要调用MovingState中的基类构造函数:

public MovingState(AI owner, string name)
    : base(owner, name)
{
}

【讨论】:

  • (S)他仍然需要调用基类构造函数或提供零参数构造函数。
  • @YotamSalmon - 您必须调用带有两个参数的基类构造函数。如果您不明确执行此操作,则会调用无参数的,但 FSMState&lt;T&gt; 上不存在任何参数,因此会出现错误。他们可以在基类中添加一个无参数的构造函数,但更有可能的是,他们只需要使用给定的参数调用现有的构造函数。
  • @Lee 这成功了,它消除了错误,我需要更多时间看看它是否真的有效
  • @Lee,现在我会给你答案,因为这消除了所有错误,谢谢!
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2021-01-29
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 2012-05-25
相关资源
最近更新 更多