XAF学习笔记之 Upcasting

https://www.cnblogs.com/foreachlife/p/xpoupcasting.html

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'"));
复制代码

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


原文地址:https://www.cnblogs.com/xyyhcn/p/11726338.html