简体   繁体   中英

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.

We can see that we are testing to see if the type is of type OrderHeader , so can't we cast to OrderHeader ?

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.

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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