【问题标题】:Passing type parameter to interface of base class将类型参数传递给基类的接口
【发布时间】:2017-03-29 13:17:29
【问题描述】:

StateBase 实现 iState

WolfState 从 StateBase 继承

WolfController 继承自 ControllerBase

我希望能够做一个

  • WolfState 使用继承自 State 的 WolfController
  • 绵羊状态 使用 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>
{
}

【问题讨论】:

  • public class WolfState : State&lt;WolfController&gt;?
  • @Lee 对不起!这就是我要写的。我已经更新了我的问题。所以这是行不通的。
  • WolfController 是否扩展 StateController?您收到的错误是什么?
  • 是的,没错。 WolfController 和 SheepController 都扩展了 StateController。 "没有从 'WolfController' 到 'IState 的隐式引用转换"

标签: c# generics inheritance polymorphism


【解决方案1】:

您似乎打算用State&lt;T&gt; 实现IState&lt;T&gt;。您当前对T 的类型有限制。将State&lt;T&gt;的定义改为:

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

【讨论】:

  • 是的!谢谢你。很高兴知道我的想法是正确的。只是不知道如何实现它。谢谢一百万!
猜你喜欢
  • 2020-10-27
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
相关资源
最近更新 更多