文章出處

 

通常,我們會定義繼承層次結構,假設有類型,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'"));

 可以看出來,只要是派生類中的屬性,就可以用<派生類型>進行轉換,后接屬性名稱即可。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()