用空类而不是枚举——糟糕的主意?
我目前正在使用枚举来描述许多可能的操作系统平台。我有 WIN32、SOLARIS64、LINUX32,还有更广泛的类别,如 ALLWIN 和 ALLUNIX。我的代码中有一个位置需要确定给定平台是否属于另一个平台的类别。对我来说,这听起来像是继承,但显然枚举不能相互继承。
然后我想到将这些平台从 1 个枚举变成相互继承的空类。我觉得这在概念上和空间上都是一个糟糕的想法,但我不是 C# 大师,我想我应该在这里发帖寻找一些更有经验的意见。有什么想法吗?
这看起来像:
public class ALL {};
public class ALLWIN : ALL {};
public class WINNT : ALLWIN{};
public class WIN32 : WINNT{};
... 等等。
I am currently using an enumeration to describe a number of possible operating system platforms. I have things WIN32, SOLARIS64, LINUX32, but also broader categories like ALLWIN and ALLUNIX. I have a place in my code where I need to decide if a given Platform falls into the category of another one. To me, this sounded like inheritance, but obviously enumerations can't inherit from each other.
I then had the thought of turning these Platforms from 1 enumeration into empty classes that inherit from each other. I feel like this is a terrible idea conceptually and spatially, but not being a master of C# I thought I'd post here looking for some more experienced opinions. Any thoughts?
This would look something like:
public class ALL {};
public class ALLWIN : ALL {};
public class WINNT : ALLWIN{};
public class WIN32 : WINNT{};
...
And so on and so forth.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
枚举不能继承,但它们具有标志的概念,可以完成您尝试做的相同事情:
等等...
链接到 枚举。
Enumerations can't inherit, but they have the concept of flags which accomplishes the same thing you are trying to do:
and so on...
Link to enumerations.
为此,您需要坚持使用枚举。您可以通过位掩码进行检查。大致如下:
当您检查平台是否属于特定系统时,您将通过执行按位 AND 来完成此操作,如以下代码所示:
这有意义吗?
You want to stick with enumerations for this. You can do the checking via a bitmask. Something along the lines of:
And when you're checking to see if the platform is of a specific system, you'll do so by doing a bitwise AND as in the following code:
Does that make sense?
设计系统的关键部分之一是能够定义您的领域。这通常也是最难的部分。我建议,退后一步。您需要定义什么?操作系统?操作系统有什么?
继承是一个强大的工具,但这种情况似乎适合“有一个”关系,而不是“是一个”关系。也许定义一个具有属性的对象,而不是让它们继承。考虑一下:
这可能与您想要实现的目标完全不同。
你怎么认为?
正如其他地方提到的,使用枚举标志可以作为一个很好的轻量级解决方案。唯一的问题是操作系统和类别的组合永远不能超过 64 种。
One of the key parts of designing a system is to be able to define your domain. This is often the hardest part as well. I would suggest, taking a step back. What is it that you need to define? An operating system? What does an operating system have?
Inheritance is a powerful tool, but this scenario seems to lend itself to a 'has a' relationship, rather than a 'is a' relationship. Instead of having them inherit, perhaps defining an object that has a property. Concider this:
This may be completely off base from what you are trying to accomplish.
What do you think?
As mentioned elsewhere using enum flags could work as a nice lightweight solution. The only catch is you can never have more than 64 combinations of operating systems and categories.