繁体   English   中英

如何将通用对象转换为MyType?

[英]How can I cast a generic object to MyType?

我得到错误

"Error  4   Cannot convert type 'TExternalEntity' to 'OTIS.Domain.InventoryMgmt.OrderHeader'"

为什么不? 我确定它与定义通用类型的where语句有关,但不确定如何解决此问题。

我们可以看到我们正在测试以查看类型是否为OrderHeader类型,所以我们不能OrderHeaderOrderHeader吗?

public ActionConfirmation<string> CreateUpdateEntity<TExternalEntity>
    (TExternalEntity entity, CompanyPreferencesFinancialsSystemCommon preferences)
        where TExternalEntity : class, OTIS.Domain.IEntity, IFinancials, new()
{

    //Determine TExternalEntity type (invoice, vendor, customer) to determine which
    //mapper class to create. Then convert TExternalEntity to TQuickbooksEntity.

    if (entity is InvoiceHeader)
    {
        var qbInvoice = new InvoiceMapper().ToQuickbooksEntity(entity as InvoiceHeader, preferences);

        return CreateUpdateQuickBooksEntity(
            qbInvoice,
            x => x.Id == entity.FinancialsId,   
            entity.FinancialsId);
    }

    if (entity is OrderHeader)
    {
        var orderHdr = (OrderHeader)entity; <------ ERROR HERE
        var qbSalesReceipt = orderHdr.ToQuickBooksEntity(preferences);

        return CreateUpdateQuickBooksEntity(
            qbInvoice,
            x => x.Id == entity.FinancialsId,
            entity.FinancialsId);
    }

您可能应该提到这是一个编译时错误,而不是运行时错误。

编译器不知道您正在测试类型,因此它认为此转换可能会失败。

评论中的任何建议都应该对您有用。

如果您使用(OrderHeader)(object)entity ,但该实体不是OrderHeader(您知道它是因为您首先对其进行测试,但很幽默),那么您会在该行上收到错误消息。

如果您将entity as OrderHeader且该实体不是OrderHeader,则orderHdr变量将设置为null并继续执行。

我还将您的示例缩减为重复该问题所需的最少代码。

public ActionConfirmation<string> CreateUpdateEntity<TExternalEntity>(TExternalEntity entity)
{
    if (entity is OrderHeader)
    {
        var orderHdr = (OrderHeader)entity; //<------ ERROR HERE
    }

    return null;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM