假设我有这个类(仅作为示例):
internal class Packet
{
private readonly UInt32 _length;
private readonly Byte _type;
private readonly UInt32 _requestId;
}
有许多不同类型的数据包,每个数据包都从该类继承,并且每个数据包类型可以具有任意数量的不同类型的属性。
有没有一种方法可以在不使用继承的情况下实现每种类型的数据包?
我考虑过使用诸如 List> 这样的属性_typesSpecificValues
- 我知道它无法编译,但我不知道如何表达我的意思。
我需要避免为每种类型的数据包创建继承类,因为大约有 50 种类型 - 或者我只是懒惰?
Lets say I have this class (just as an example):
internal class Packet
{
private readonly UInt32 _length;
private readonly Byte _type;
private readonly UInt32 _requestId;
}
There are many different types of packets each of which inherit from this class and each packet type can have any number of properties of varying types.
Is there a way to implement every type of packet without using inheritance?
I thought about using a property such as List<Tuple<Type,Value>> _typesSpecificValues
- I know it won't compile but I don't know how else to express what I mean.
I need to avoid creating an inheriting class for each type of packet because there are about 50 types - or am I just being lazy??
发布评论
评论(4)
听起来您应该创建单独的类,是的。
但是,我不确定是否会让它们从此类派生。听起来这应该位于
Header
类(甚至可能是结构体)中,然后您可以拥有多个类,每个类包含一个Header
。It sounds like you should be creating separate classes, yes.
However, I'm not sure whether I'd make them derive from this class. It sounds like this should be in a
Header
class (or possibly even a struct) and then you could have multiple classes which each contain aHeader
.根据您的简短描述,听起来更像是结构而不是类。再看看你的 50 多个不同的定义,并尝试看看它们到底有什么不同。例如,如果一半以一种方式处理,一半以另一种方式处理,也许您实际上只有两个知道如何处理不同结构的类。
Based on your brief description it sounds more like they should be structs instead of classes. Take a second look at your 50+ different definitions and try to see what is really different about them. For example, if half get processed one way and half another maybe you really just have two classes that know how to deal with the different structs.
您需要问自己的是:单独使用“Packet”是否有意义?。您会在所有/大多数用途中访问基类的属性吗?
例如,假设您有:
访问 CommPacket.Length 是典型的吗?或者将 CommPacket 传递给某个接受 Packet 作为参数的类是否有意义?如果其中任何一个的答案是“是”,则您应该使用基类。
What you need to ask yourself is: does is make any sense to use 'Packet' by itself?. Will you be accessing the base class's properties in all/most uses?
For example, let's say you have:
Would it be typical to access CommPacket.Length? Or would it ever make sense to pass a CommPacket to some class that accepted a Packet as a parameter? If the answer to either of these is Yes, you should be using a base class.
如果您有这么多不同类型的类,并且它们之间具有许多不同的特性,那么您不应该使用继承,而应该使用组合。
阅读这篇文章,它比我解释得更好。
编辑
阅读这本关于装饰器模式的更好章节,来自优秀的书籍首先:设计模式
为了确保我让您注意这本书,这里有一些屏幕截图:
继承
组合
If you have so many different types of classes with many diverse caracteristics between them you should not use inheritance but instead you should use Composition.
Read this article that explains it way better than I could.
EDIT
Read this even better chapter about the decorator pattern from the excellent book Head First: Design Patterns
To make sure I get you attention to this book here there are some screenshots:
Inheritance
Composition