问题
Using delphi 7, I have a TCollection/TCollectionItem set of descendents. They are intended to be set up in Design-time only, and should never be modified in Run-time. How can I do this? Design-time should always allow whatever edits are needed, but in Run-time, I don't want to be able to Add, Remove, or Re-index any of the items in the collection. The properties of each of those items, yes, I do want them to be enabled. But changing the actual items around shall only be in design-time.
回答1:
You can override the Assign()
and Notify()
methods of TCollection
to be notified of adds and deletes, and override the SetIndex()
method of TCollectionItem
to be notified of reindexings. For adds/deletes, throw an exception to reject the operation (in the case of add, you will have to free the new item that was added). For reindexing, just exit without doing anything.
To differentiate between run-time and design-time, walk through the Owner chain of TCollection
(in case it is nested inside of other classes) until you find a TComponent
, then you can check its ComponentState
property for the csDesigning
flag.
来源:https://stackoverflow.com/questions/8072588/delphi-tcollection-possible-to-prevent-changing-items-in-run-time