简体   繁体   English

为不同的子抽象类覆盖抽象方法 C#

[英]Overriding Abstract Method C# for different child abstract classes

public abstract class Problem
{
    public abstract List<Action> GetPossibleActions(State currentState);
}

Here both Action and State classes are also Abstract Classes.这里的 Action 和 State 类也是抽象类。

In the child class of Problem, I am implementing that abstract method with using children of Action and State.在问题的子 class 中,我正在使用 Action 和 State 的子级来实现该抽象方法。 Now it gives me error because I didnt use the same Abstract classes for return type and argument.现在它给了我错误,因为我没有对返回类型和参数使用相同的抽象类。

public class PizzaProblem : Problem
{
    public List<PizzaAction> GetPossibleActions(PizzaState currentState)
    {
       ......
    }

}

You could make your class a generic class:您可以使您的 class 成为通用 class:

public abstract class Problem<TAction, TState>
  where TAction : Action
  where TState : State
{
    public abstract IList<TAction> GetPossibleActions(TState currentState);
}

public class PizzaProblem : Problem<PizzaAction, PizzaState> { ...

Or don't care about the concrete type contained in your list: rely on polymorphism to call the correct methods.或者不关心列表中包含的具体类型:依靠多态性来调用正确的方法。

The signature needs to stay the same way as in the abstract class.签名需要保持与抽象 class 相同的方式。 Try尝试

public List<Action> GetPossibleActions(State currentState)
{
    // Your code
}

Also Action is an object for it self. Action 本身也是一个 object。 If you didn't define the PizzaAction type which inherits from action, it won't work.如果您没有定义从 action 继承的 PizzaAction 类型,它将不起作用。 Same is valid for State.同样适用于 State。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM