Using an enum with generics

后端 未结 2 1049
太阳男子
太阳男子 2021-01-06 02:40

I\'m trying to create a generic class to which I can use a set of enums to initiate the values inside. For example:

constructor TManager.Create         


        
2条回答
  •  被撕碎了的回忆
    2021-01-06 02:56

    You cannot constrain a generic parameter such that low() and high() can be used in the generic class. The only constraints available are class or interface constraints.

    To the very best of my knowledge, the language offers no generic way to enumerate over a generic enumerated type. Probably the best you can do is to use RTTI, sacrificing compile time type safety (as illustrated by Tobias).


    Having read the comments to Tobias's answer, it seems likely that what you really want here is TObjectDictionary. That's because you want to be able to find a TMyObject instance given a TEnum key. And you want TObjectDictionary rather than TDictionary because the former takes over ownership of the TMyObject instances. You need somebody to free them all when you are done, and you may as well let TObjectDictionary do it for you.

    For an example of the ownership side of this, see @RRUZ's answer here: Example for using Generics.Collections.TObjectDictionary

提交回复
热议问题