存储枚举的列表类?
我应该使用什么列表类型来存储枚举值?我尝试过使用 TObjectList,我将其转换为 TObject 以添加值,但在从列表中读取时无法将其转换回枚举。
你用什么列表来存储枚举?
What List type I should use to store enum values? I have tried with TObjectList, I cast to TObject to Add the value, but can't cast it back to enum when reading from the list.
What list do you use to store enums?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将枚举转换为
Pointer
或TObject
并返回效果很好。如果您的 Delphi 版本支持泛型,请使用 Tim 的建议,效果会更好。或者,您可以使用动态数组(TTestEnum 数组
)或围绕动态数组创建一个包装类 - 这就是在支持泛型的 Delphi 版本中实现泛型列表的方式。这是一个快速控制台演示,使用
TList
,而不是TObjectList
,因为TList
对它所保存的项目做出的假设较少。Casting enums to
Pointer
orTObject
and back works just fine. If your Delphi version supports generics use Tim's suggestion, it's better. Alternatively you can use an dynamic array (array of TTestEnum
) or create a wrapper class around the dynamic array - that's how generic lists are implemented in Delphi versions capable of generics.Here's a quick console demo, using
TList
, notTObjectList
becauseTList
makes fewer assumptions about the items it holds.你不能只使用泛型吗?
Could you not just use Generics for this?
这个答案可能会有所帮助。它是通过创建后代来将记录存储在 TList 中以避免所有类型转换。请注意,您无需担心为枚举值分配/释放内存,因为它们是适合指针空间的简单序数类型。
请注意,当
Add
到列表时,您必须类型转换为Pointer
,并且在读回时可能必须类型转换为 `YourEnum(Integer(List[Index]))。但是,我链接到的代码显示了如何在后代类中处理这两种情况,因此每种方式只完成一次,并且隐藏在类实现中。This answer may help. It's about storing records in a TList by creating a descendant to avoid all the typecasting. Note that you won't need to worry about allocating/freeing memory for the enum values, as they're simple ordinal types that fit in the space of a pointer.
Note that you have to typecast to
Pointer
whenAdd
ing to the list, and may have to typecast as `YourEnum(Integer(List[Index])) when reading back. However, the code I linked to shows how to handle both in the descendant class so it's only done once each way, and that's buried in the class implementation.