文章出處
文章列表
通常,我們會定義繼承層次結構,假設有類型,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'"));
可以看出來,只要是派生類中的屬性,就可以用<派生類型>進行轉換,后接屬性名稱即可。
文章列表
全站熱搜