简体   繁体   English

从派生类型转换为基类型

[英]Casting from derived type to base type

Given that 鉴于

public abstract class AbstractOrder
{
    //some properties...
}

public class AnonymousOrder:AbstractOrder
{
    //some properties...
}


public class PartnerOrder:AbstractOrder
    {
        //some properties...
    }


public AbstractOrder FindOrderByConfirmationNumber(string confirmationNumber)
{
    ICriteria criteria =
        Session.CreateCriteria(typeof(AbstractOrder))
            .SetMaxResults(10)
            .AddOrder(Order.Desc("PurchasedDate"))
            .Add(Restrictions.Eq("ConfirmationNumber", confirmationNumber));
    var l = criteria.List<AbstractOrder>();
    AbstractOrder ao = l[0] as AbstractOrder;
    return ao as AbstractOrder;
}

Can someone please explain why 有人可以解释原因

PartnerOrder order = repo.FindOrderByConfirmationNumber(confirmationNumber)

returns a type of AnonymousOrder and how I get it to return a type of PartnerOrder? 返回一种AnonymousOrder以及如何让它返回一种PartnerOrder?

AbstractOrder is an Abstract class. AbstractOrder是一个抽象类。 No object can ONLY be an abstract class, it can inherit from it as a base class but it is always something else as well. 没有对象只能是一个抽象类,它可以作为基类从它继承,但它也总是其他东西。

It's returning type AnonymousOrder which is the most specific class it is, but it also an AbstractOrder. 它返回的类型是AnonymousOrder,它是最具体的类,但它也是一个AbstractOrder。 You can treat it as just an AbstractOrder, nothing should be effected. 您可以将其视为AbstractOrder,不应该有任何影响。

FindOrder is returning a type of AbstractOrder ; FindOrder 返回一个类型的AbstractOrder ; just look at its declaration. 看看它的宣言。 The object it returns may be an instance of AnonymousOrder , but all AnonymousOrder instances are also AbstractOrder instances, because AnonymousOrder inherits from AbstractOrder . 它返回的对象可能是AnonymousOrder一个实例,但所有AnonymousOrder实例也是AbstractOrder实例,因为AnonymousOrder继承自AbstractOrder

I think your real problem is trying to assign an AnonymousOrder instance to a PartnerOrder reference. 我认为您真正的问题是尝试将AnonymousOrder实例分配给PartnerOrder参考。 This won't work, since neither type is derived from the other. 这不起作用,因为这两种类型都不是派生的。

This, however, will work: 但是,这将起作用:

AnonymousOrder order = (AnonymousOrder)repo.FindOrderByConfirmationNumber(confirmationNumber);

Alternatively, you could test the type of the return value: 或者,您可以测试返回值的类型:

AbstractOrder order = repo.FindOrderByConfirmationNumber(confirmationNumber);
PartnerOrder partnerOrder = order as PartnerOrder;
if (partnerOrder != null)
    //...

If you really need a PartnerOrder instance for a confirmationNumber that returns an AnonymousOrder, then you'll need a method that takes an AnonymousOrder instance and returns a PartnerOrder instance. 如果您确实需要一个返回AnonymousOrder的confirmationNumber的PartnerOrder实例,那么您将需要一个采用AnonymousOrder实例并返回PartnerOrder实例的方法。 Or, perhaps, you should rethink your design. 或许,您应该重新考虑您的设计。

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

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