【发布时间】:2016-02-26 22:12:21
【问题描述】:
我将基类型列表转换为派生类型列表
List<TicketDetail> ticketDetails = listResult.Cast<TicketDetail>().ToList();
List<TicketDetail> ticketDetails = listResult.ConvertAll(x => (TicketDetail) x).ToList();
我都试过了,每一个都扔了:
System.InvalidCastException:无法转换类型的对象 “WorkOrder.Service.Ticket”键入“WorkOrder.Service.TicketDetail”。 这是我的课
namespace WorkOrder.Service
{
using System;
[DataContract]
[KnownType(typeof(TicketDetail))]
public partial class Ticket
{
public int RecordId { get; set; }
public long TicketId { get; set; }
public string Summary { get; set; }
public string Details { get; set; }
public int CategoryId { get; set; }
public System.DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public string Status { get; set; }
public string TicketSource { get; set; }
public string TicketType { get; set; }
public string ManagedByGroup { get; set; }
public string ManagedByUser { get; set; }
public Nullable<long> SubscriptionId { get; set; }
public string PriorityLevel { get; set; }
public string Impact { get; set; }
public string ImpactOnBusiness { get; set; }
public string Risk { get; set; }
public string Comment { get; set; }
public Nullable<System.DateTime> PlannedStartDatetime { get; set; }
public Nullable<System.DateTime> ActualStartDatetime { get; set; }
public Nullable<System.DateTime> PlannedDeadlineDatetime { get; set; }
public Nullable<System.DateTime> ActualDeadlineDatetime { get; set; }
public System.DateTime TransactionDatetime { get; set; }
public string AssignedToGroup { get; set; }
public string AssignedToUser { get; set; }
public string CategoryName { get; set; }
public int CreatedById { get; set; }
public int StatusId { get; set; }
public int SourceId { get; set; }
public int TypeId { get; set; }
public int ManagedByGroupId { get; set; }
public Nullable<int> ManagedByUserId { get; set; }
public int AssignedToGroupId { get; set; }
public Nullable<int> AssignedToUserId { get; set; }
public int PriorityLevelId { get; set; }
public int ImpactLevelId { get; set; }
public int ImpactOnBusinessLevelId { get; set; }
public int RiskLevelId { get; set; }
}
}
派生类:
namespace WorkOrder.Service
{
[DataContract]
public class TicketDetail : WorkOrder.Service.Ticket
{
[DataMember]
public List<WorkLogView> WorkLogs { get; set; }
}
}
【问题讨论】:
-
除非该对象首先创建为派生类型,否则您不能将基类型转换为派生类型....如何解决?在采用基类型的派生类型中使用构造函数。如果你想要一种快速的方法,你必须一个一个地复制这些对象。其他明智的使用反射很慢。
-
OP 正在使用
KnownType来解决问题。可能是服务没有返回正确的类型。因此,我不得不投票重新开放。 -
您的服务代码是什么样的?方法返回什么?您是否更新了服务参考?