c# - 如何在基类中使用逆变参数?

标签 c# inheritance asp.net-web-api contravariant

在 ASP.NET Web API 2.0 项目中,我想使用 HTTP 动词 GETPOST 访问数据模型中的类似对象,所有对象都实现接口(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/

相关文章:

c# - 有谁知道用于Windows Phone的OCRing 7段显示器的任何API?

c# - 调用以 std::list 作为参数的 C++ 函数

jquery - 更新到 5.1.0 后将数据 POST 到 WebApi 失败

c# - dnn WebApi - DnnAuthorize 方法不起作用?

c# - 捕获 WebAPI 方法调用的响应大小(以字节为单位)

c# - 垂直显示的字母排序列表

c# - Application.UserAppDataPath 奇怪的行为

java - 继承类型问题: is there a clean solution?

c++ - 如何从一组派生类创建一个列表?

java - 如何在子类中使用泛型来限制方法参数类型?