简体   繁体   中英

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.

In the child class of Problem, I am implementing that abstract method with using children of Action and 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:

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. Try

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

Also Action is an object for it self. If you didn't define the PizzaAction type which inherits from action, it won't work. Same is valid for State.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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