这是我正在尝试寻找合适设计的情况。
我需要存储号码的配置文件。配置文件只是一系列数字。它们可以是 int、float 或decimal 类型。每个配置文件都有一个基于枚举的 ProfileDescription 字段。
每个配置文件都有一个 ProfileVersion 对象的集合。每个 ProfileVersion 对象都有一个 ProfileValue 对象的集合。这些 ProfileValue 对象是存储所需类型的实际数值的位置。
我最初的设计想法是使 Profile、ProfileVersion 和 ProfileValue 通用。当我想要拥有不同类型的配置文件列表时,我遇到了一个问题,但我无法拥有。我可以使用 ArrayList 来代替,但随后我必须抛出其中的数据。
我虽然可以仅使 ProfileVersion 和 ProfileValue 通用,然后让配置文件对象根据 ProfileDescription 字段的值向 ProfileVersion 分配类型,但我找不到方法来执行此操作。
另一个想法是我应该使用 ProfileBase 类,然后使用 GenericProfileClass 或 IntProfile、FloatProfile 和 DecimalProfile 对其进行子类化,但这并不会真正给我带来任何比让每个类都是通用的优势,因为我必须强制转换无论如何,每次都会退出子类。
非常感谢您对这种情况的最佳设计方法的想法。
谢谢
最佳答案
Grzenio的想法是正确的。您的每个配置文件类都可以成为 IProfile
对象的实现,然后您的容器可以是:
class ProfileList : IList<T> where T: IProfile
因此,您拥有的唯一约束是接口(interface),而不是特定类型或强制转换的基类。
至于:
Another thought was I should use a ProfileBase class and then subclass it with either a GenericProfileClass or IntProfile, FloatProfile and DecimalProfile, but this wouldn't really give me any advantage over having each class being generic, as I would have to cast out the subclass each time anyway.
好处实际上取决于您为类创建的抽象级别。如果设计得当,理想情况下,您可以拥有可以接受任何这些基类型(再次通过泛型)的操作/业务逻辑/或管理器类,而无需知道特定的强制转换。
关于c# - OOGenerics 设计注意事项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/653698/