简体   繁体   English

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

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

I get the error 我得到错误

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

Why not? 为什么不? I'm sure it has something to do with the where statement defining the generic type, but not exactly sure how to get around this. 我确定它与定义通用类型的where语句有关,但不确定如何解决此问题。

We can see that we are testing to see if the type is of type OrderHeader , so can't we cast to OrderHeader ? 我们可以看到我们正在测试以查看类型是否为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);
    }

You should probably mention that this is a compile-time error, not a run-time error. 您可能应该提到这是一个编译时错误,而不是运行时错误。

The compiler doesn't know that you are testing the type, so it sees that this cast will potentially fail. 编译器不知道您正在测试类型,因此它认为此转换可能会失败。

Either of the suggestions in the comments should work for you. 评论中的任何建议都应该对您有用。

If you use (OrderHeader)(object)entity and the entity is not an OrderHeader (you know it is since you are testing for it first, but humor me), then you would get an error on that line. 如果您使用(OrderHeader)(object)entity ,但该实体不是OrderHeader(您知道它是因为您首先对其进行测试,但很幽默),那么您会在该行上收到错误消息。

If you use entity as OrderHeader and the entity is not an OrderHeader, the orderHdr variable would be set to null and execution would continue. 如果您将entity as OrderHeader且该实体不是OrderHeader,则orderHdr变量将设置为null并继续执行。

I also trimmed your example down to the minimum code required to duplicate the issue. 我还将您的示例缩减为重复该问题所需的最少代码。

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