如何在C#中将子类型转换为父对象 [英] how to typecast Child to Parent object in C#
问题描述
我有一个 ASP.Net Core 2.1 C#
应用程序.
这就是我的DTO的样子.
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;}
}
机票(基本舱位)
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控制器
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
无法转换类型的对象'System.Collections.Generic.List
1 [Ticket]'键入'System.Collections.Generic.List
1 [TicketSpecial]'
Unable to cast object of type 'System.Collections.Generic.List
1[Ticket]' to type 'System.Collections.Generic.List
1[TicketSpecial]'
此外,TicketSpecial的额外属性不可用,因为它不在Ticket类中.
Also,the extra properties of TicketSpecial is unavailable as it's not present in Ticket class.
所以我反之亦然
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
}
}
但是这引发了错误,因为CS0266无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.IEnumerable'.存在显式转换(您是否缺少演员表?)
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?)
我想使用#2(第二种方式)解决此问题,因为在 move.IsSpecial
为true
如何处理这种类型转换?谢谢!
How to handle this typecasting? Thanks!
推荐答案
必须准备电影中的特殊票的清单.这些票并传递给消费者
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);
在您的示例中,第二个分配将Tickets属性分配回原始属性,原始属性是票证列表,而不是特殊票证.
In your example, the second assignment assigned the tickets property back to the original one which is a list of ticket, not special ticket.
这篇关于如何在C#中将子类型转换为父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!