XAF学习笔记之 Upcasting

 

通常,我们会定义继承层次结构,假设有类型,CustomerBase,CustomerTrialed,CustomerRegistered三个类型,并且继承结构如下:

 

 

业务对象代码定义如下:

 

using DevExpress.Xpo;

public class CustomerBase : XPObject {
    string fCustomerName;
    private string fEmail;
    public CustomerBase(Session session) : base(session) { }

    public string CustomerName {
        get { return fCustomerName; }
        set { SetPropertyValue("CustomerName", ref fCustomerName, value); }
    }
    public string Email {
        get { return fEmail; }
        set { SetPropertyValue("Email", ref fEmail, value); }
    }
}

public class CustomerRegistered : CustomerBase {
    string fOwnedProducts;
    public CustomerRegistered(Session session) : base(session) { }
    
    public string OwnedProducts {
        get { return fOwnedProducts; }
        set { SetPropertyValue("OwnedProducts", ref fOwnedProducts, value); }
    }
}

public class CustomerTrialed : CustomerBase {
    string fTrialedProducts;
    public CustomerTrialed(Session session) : base(session) { }

    public string TrialedProducts {
        get { return fTrialedProducts; }
        set { SetPropertyValue("TrialedProducts", ref fTrialedProducts, value); }
    }
}

我们可以使用如下代码进行查询所有客户的数据。

XPCollection<CustomerBase> allCustomers = new XPCollection<CustomerBase>(session1);
这个集合的类型是CustomerBase,所以你只能访问CustomerBase类型的属性。不能够访问派生类的属性,例如,OwnedProducts 属性,即使集合中包含 CustomerRegistered 对象。这是因为基类类型不知道 OwnedProducts 属性。

要突破限制,请使用Upcasting功能。

如果要显示属性的内容时,可以修改该集合的 XPBaseCollection.DisplayableProperties 属性。设置为这样:"Oid;CustomerName<CustomerRegistered>OwnedProducts"。

在这里,"Oid;CustomerName"是属性值的一部分,<CustomerRegistered>OwnedProducts 是派生类中的属性。

 

构建查询条件时,也可以使用相同的语法。例如,若要检索所有已购买或评估 XtraGrid 的客户,请使用下面的代码。
XPCollection<CustomerBase> gridCustomers = new XPCollection<CustomerBase>(session1, 
CriteriaOperator.Parse(
"<CustomerRegistered>OwnedProducts = 'XtraGrid' or <CustomerTrialed>TrialedProducts = 'XtraGrid'" 
 ));

 

请使用以下语法对引用类型属性的查询。

 

public class Invoice : XPObject {
    CustomerBase fCustomer;
    public Invoice(Session session) : base(session) { }

    // This is a reference type property. It can reference any CustomerBase descendant. 
    public CustomerBase Customer {
        get { return fCustomer; }
        set { SetPropertyValue("Customer", ref fCustomer, value); }
    }
}

// Uses upcasting to access CustomerRegistered properties. 
XPCollection<Invoice> invoices = new XPCollection<Invoice>(session1,
  CriteriaOperator.Parse("Customer.<CustomerRegistered>OwnedProducts = 'XtraGrid'"));

 可以看出来,只要是派生类中的属性,就可以用<派生类型>进行转换,后接属性名称即可。

posted @ 2016-01-11 10:15  code first life  阅读(1685)  评论(0)    收藏  举报