how to typecast Child to Parent object in C#

主宰稳场 提交于 2020-02-06 07:28:43

问题


I have an ASP.Net Core 2.1 C# application.

This is how my DTOs looks like.

public class Movie
{
  public int Id { get; set;}

  public bool IsSpecial {get; set;}

  public IEnumerable<Ticket> Tickets{ get; set;}
}

Tickets (Base Class)

 public class Ticket
 {
   public int Id { get; set;}

   public string Name { get; set;}

   public decimal price { get; set;}
 } 

TicketsSpecial (Child/Derived Class)

 public class TicketsSpecial : Ticket
 {
    public string SpecialProp1 { get; set;}

    public string SpecialProp2 { get; set;}

 }

WebAPI Controller

public class MovieController : ControllerBase
{

  public IActionResult Post([FromBody]Movie movie)
  {
      if(movie.IsSpecial)
      {
         var tickets = movie.Tickets;
         movie.Tickets = new List<TicketsSpecial>(); 
        movie.Tickets = tickets;
         SomeMethod(movie.Tickets);// throws run time error
         movie.Tickets = tickets;
      }
  }

  private bool SomeMethod(IEnumerable<TicketSpecial> tickets)
  {
  }
}

RTE

Unable to cast object of type 'System.Collections.Generic.List1[Ticket]' to type 'System.Collections.Generic.List1[TicketSpecial]'

Also,the extra properties of TicketSpecial is unavailable as it's not present in Ticket class.

so I tried vice-versa

public class Movie
{
  public int Id { get; set;}

  public IEnumerable<TicketSpecial> Tickets{ get; set;}
}

Going this way, I get the values of extra fields ie. TicketSpecial props. But again while typecasting it throws the error.

public IActionResult Post([FromBody]Move movie)
  {
      if(!movie.IsSpecial)
      {
         var tickets = movie.Tickets;
         movie.Tickets = new List<Ticket>();//throws Compile time error 

      }
  }

But this throws the error as CS0266 Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

I want to address this with #2 (second way) as I would have the extra props value in case move.IsSpecial is true

How to handle this typecasting? Thanks!


回答1:


Must prepare a list of special tickets from movie.Tickets and pass to the consumer

var specialTickets = new List<TicketsSpecial>();
specialTickets.AddRange(movie.Tickets.OfType<TicketsSpecial>());
SomeMethod(specialTickets);

In your example, the second assignment assigned the tickets property back to the original one which is a list of ticket, not special ticket.



来源:https://stackoverflow.com/questions/58372592/how-to-typecast-child-to-parent-object-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!