c# - 设计问题: Get child object type information avoiding if statements in presentation layer

标签 c# asp.net design-patterns architecture polymorphism

我有这样的客户层次结构:

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/

相关文章:

c# - <asp :FileUpload> doesn't have a file

c# - 管理引用计数和对象生命周期的模式

java - 如何按类类型委托(delegate)给服务?

c# - 在 ASP.NET MVC 5 中将图像添加到数据库

c# - 瑞典文化信息

c# - 将类转换为 xml 的最佳方法是什么,反之亦然

c# - 重构 if-else if - else

c# - 内联 css 声明中的 .net Razor 代码块

asp.net - 如何创建基于Web的可视化流程设计器?

asp.net - 使用 Paypal 订阅(Netflix 风格)