将类型参数传递给基类的接口

时间:2017-03-29 13:17:29

标签: c# generics inheritance polymorphism

StateBase实现iState

来自StateBase的WolfState ineherits

WolfController继承自ControllerBase

我希望能够做到

  • 使用从状态继承的WolfController的WolfState
  • SheepState 它使用SheepController并继承自State

WolfController和SheepController都将从StateController继承。

我应该如何声明WolfState?

我尝试这样做的方式不起作用。

   public interface IState <T> where T : StateController 
{
}

public abstract class State<T> where T : StateController,  IState<T> 
{
}

// THIS IS HOW I WOULD LIKE TO DO IT BUT ITS NOT ACCEPTED
public class WolfState : State<WolfController>
{
}

public class SheepState : State<SheepController>
{
}

1 个答案:

答案 0 :(得分:1)

您似乎打算State<T>来实施IState<T>。您目前对T的类型有约束。将State<T>的定义更改为:

public abstract class State<T> : IState<T> where T : StateController
{
}