我有这样的客户层次结构:
abstract class Customer {
public virtual string Name { get; set; }
}
class HighValueCustomer : Customer {
public virtual int MaxSpending { get; set; }
}
class SpecialCustomer : Customer {
public virtual string Award { get; set; }
}
当我检索客户时,我想在 Web 表单上显示要编辑/修改的属性。目前,我使用 if 语句来查找子客户类型并显示专门的属性。是否有设计模式(访问者?)或更好的方法可以避免表示层中的“if”语句?你是怎么做到的?
更多信息:这是一个带有 nHibernate 后端的 asp.net 网站。每种客户类型在页面上都有自己的用户控件,我希望根据客户类型自动加载该控件。
最佳答案
您可以使用反射来获取特定于子类(实例)的属性列表吗? (不易出错。)
如果没有,创建一个返回特殊属性的(虚拟)方法。 (更容易出错!)
以后者为例:
abstract class Customer {
public virtual string Name { get; set; }
public virtual IDictionary<string, object> GetProperties()
{
var ret = new Dictionary<string, object>();
ret["Name"] = Name;
return ret;
}
}
class HighValueCustomer : Customer {
public virtual int MaxSpending { get; set; }
public override IDictionary<string, object> GetProperties()
{
var ret = base.GetProperties();
ret["Max spending"] = MaxSpending;
return ret;
}
}
class SpecialCustomer : Customer {
public virtual string Award { get; set; }
public override IDictionary<string, object> GetProperties()
{
var ret = base.GetProperties();
ret["Award"] = Award;
return ret;
}
}
无论如何,您可能想在您的网页上创建部分(fieldset
?),所以 if
会在那里发挥作用,使这种额外的编码有点烦人并且没用。
关于c# - 设计问题: Get child object type information avoiding if statements in presentation layer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/636994/