在 ASP.NET Web API 2.0 项目中,我想使用 HTTP 动词 GET
和 POST
访问数据模型中的类似对象,所有对象都实现接口(interface) ITableRow
。所以我有一个基类提供访问这些模型类的默认实现:
class ControllerBase
{
protected string whereAmI = "base controller";
public IHttpActionResult Get(int id)
{
Console.WriteLine(whereAmI + ": GET");
[... here is the default action to get the data object(s) ...]
}
public IHttpActionResult Post([FromBody] ITableRecord value)
{
Console.WriteLine(whereAmI + ": POST " + value.GetType().ToString());
[... here is the default action to create a new data object ...]
}
}
以及一个想要使用 Post()
的 ControllerBase
默认实现的派生类:
public class ElementsController : ControllerBase
{
protected string whereAmI = "element controller";
}
使用 GET 路由很简单,但调用 POST 路由有问题:
通过 Post 的 Web API 2.0 框架自动调用现在调用 ElementsController.Post()
方法,但无法创建元素对象,因为它只知道必须构建 ITableRecord
对象作为值 - 由于这只是一个接口(interface),因此变量 value
保持 null
。
现在我可以在每个派生类中编写 Post()
的特定定义,从那里调用 ControllerBase.Post()
:
public override IHttpActionResult Post([FromBody] Element value) // this won't work since the argument types doesn't fit
{
return base.PostHelper(value); // so I have to call a helper function in base
}
我的问题是:是否有更好的(比如:更干燥)方法来告诉派生类 Post()
方法的参数必须是哪种特定类型,而不需要?
最佳答案
这看起来像是泛型的工作。首先,使基类成为泛型,然后更改 Post
方法以使用泛型类型。例如:
// Note the type constraint too, you may not want this depending on your use case
class ControllerBase<T> where T : ITableRecord
{
public IHttpActionResult Post([FromBody] T value)
{
//...
}
}
现在你的派生 Controller 将如下所示:
public class ElementsController : ControllerBase<Element>
{
//...
}
关于c# - 如何在基类中使用逆变参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65124131/