简体   繁体   English

记录中的Delphi Stringlist

[英]Delphi Stringlist in Record

Is it possible to have a stringlist in a record? 是否有可能在记录中有一个字符串列表? EG 例如

TImportStats = record
  ATotal:Integer;
  BTotal:String;
  AList:TStringist;
end;

and if I presume I would need to create it before using the record? 如果我认为我需要在使用记录之前创建它?

Whilst this is perfectly legal, it may be prudent to find another way. 虽然这是完全合法的,但找到另一种方式可能是谨慎的。 You pinpoint the issue when you said: 当你说:

I presume I would need to create it before using the record 我认为我需要在使用记录之前创建它

Not only that, but you need to find a good time to destroy it too. 不仅如此,你还需要找到一个摧毁它的好时机。 If you forget to do so there will be no errors but your program will leak memory. 如果您忘记这样做将没有错误,但您的程序将泄漏内存。

If the record is the owner of the string list then you may be better off containing it inside a class. 如果记录是字符串列表的所有者 ,那么最好将其包含在类中。 That way the construction and destruction of the string list will follow the constructor/destructor pattern that all Delphi developers are familiar with. 这样,字符串列表的构造和销毁将遵循所有Delphi开发人员都熟悉的构造函数/析构函数模式。

If the record does not own the string list, but just takes a reference to it during the lifetime of the string list, then a record is fine. 如果记录不拥有字符串列表,但只是在字符串列表的生命周期内对它进行引用,那么记录就可以了。 But if you do it this way make sure that the record's lifetime is contained within the string list's lifetime so that you don't carry around a stale reference. 但是如果你这样做,请确保记录的生命周期包含在字符串列表的生命周期内,这样你就不会携带陈旧的引用。

Yes, this should work. 是的,这应该有效。 AList will (not be useable) until you create the stringlist. 在创建字符串列表之前,AList将(不可用)。 So you can use other elements of the record without creating the stringlist, but you must create the stringlist element prior to using it. 因此,您可以在不创建字符串列表的情况下使用记录的其他元素,但必须在使用之前创建stringlist元素。 Also, you are responsible for freeing each stringlist when you're done. 此外,您还有责任在完成后释放每个字符串列表。

If the stringlist is only going to be used in the local scope of the TImportStats record, you might want to look at a StringList value implementation in Code Central. 如果stringlist仅用于TImportStats记录的本地范围,您可能希望查看Code Central中的StringList值实现

This avoids the try, create, finally, destroy overhead. 这样可以避免尝试,创建,最终破坏开销。

I know it's probably late, but the most elegant way to solve your problem, would be to create a subclass of TStringList with ATotal and BTotal as the two new elements in it. 我知道它可能已经晚了,但解决问题的最优雅的方法是创建一个TStringList的子类,其中ATotal和BTotal作为其中的两个新元素。 Then you can simply create and destroy it as you see fit. 然后你可以根据需要简单地创建和销毁它。 This solution is clean and simple. 这个解决方案简洁明了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM