c#REST API多态返回类型

Kav*_*tty 3 c# polymorphism inheritance response asp.net-web-api

我创建了数据合同,如下所示: -

[DataContract(Name = "Animal")]
public class Animal { ... }

[DataContract(Name = "Dog ")]
public class Dog : Animal { // Has some Dog specific member properties }

[DataContract(Name = "Cat ")]
public class Cat : Animal { // Has some Cat specific member properties }
Run Code Online (Sandbox Code Playgroud)

我正在使用ASP.NET WebApi来提供REST API,如:

[HttpGet]
public Task<Animal> Get(string type) 
{ 
    switch(type)
    {
        case "dog":
            Dog dog = GetDogDetails();
            return Task.FromResult(dog);
            break;

        case "cat":
            Cat cat = GetCatDetails();
            return Task.FromResult(cat);
            break:
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法归还各自的动物类型.我收到以下错误: - "无法隐式将Dog转换为Animal".

根据REST API标准,这种多态响应也是一件好事.

Vla*_*pko 6

您收到此错误的原因是因为您正在返回a Task<T>并且任务不是协变的.也就是说,即使DogAnimal,Task<Dog>也不是Task<Animal>.

你能做什么?

  1. 将代码更改为

        case "dog":
        Animal dog = GetDogDetails();
        return Task.FromResult(dog);
        break;
    
    Run Code Online (Sandbox Code Playgroud)

但是你会失去狗的特定属性.

  1. 杠杆Task<IHttpActionResult>和回报Ok(yourObject).

    [HttpGet]
    public async Task<IHttpActionResult> Get(string type) 
    { 
        switch(type)
        {
            case "dog":
                Dog dog = GetDogDetails();
                return Ok(dog);
                break;
    
        ...
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

我认为你应该走第二条道路.

在第二点,我真的没有理由在async/await这里使用.你为什么要用Task.FromResult?如果您的GetDogDetails方法是async,请考虑awaiting它.我认为您不应该担心当前代码中的任务.

根据REST API标准,这种多态响应也是一件好事.

我不知道正式的标准,但一般情况下,某些对象可以拥有某些属性而其他对象则不可以.例如,假设一个支付系统返回一个抽象事件,该事件可能有也可能没有相关的发票.