我有几个类(class)
Square : Rectangle : Shape (abstract)
我有一个继承自 ApiController 的基础 Controller ,我想使用它。
public abstract class BaseController<T> : ApiController where T : class
{
public abstract IEnumerable<T> Get()
...
}
和
public class DerivedController : BaseController<Rectangle>
{
public override IEnumerable<Rectangle> Get()
...
}
public class AnotherDerivedController : BaseController<Square>
{
public new IEnumerable<Square> Get()
...
}
/api/rectangle 将正确调用 IEnumerable<Rectangle> Get()
/api/square 会给我一个错误:
Multiple actions were found that match the request:
System.Linq.IEnumerable`1[Square] Get() on type Web.Api.Controllers.AnotherDerivedController
System.Linq.IEnumerable`1[Rectangle] Get() on type Web.Api.Controllers.DerivedController
如果我改变 public new IEnumerable<Square> Get()
至 public override IEnumerable<Square> Get()
, 由于返回的签名不同,我得到一个编译时错误
如何让我的代码调用正确的方法?是否需要在RegisterRoutes中显式注册每个类的方法?
最佳答案
您需要覆盖 Get,您基本上是将它与 new
一起使用。这是行不通的,因为类将有两个 Get 方法,Web API 会混淆选择哪一个。
您可以将 BaseController
定义为 abstract
并将 Get
定义为 virtual
或 abstract
> 然后在您的 DerivedController
中实现。
关于c# - 继承的 Web API API Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10218963/