Another option is to use RTTI. The code below works like a normal method in my class as a way to get a new instance of an object with a subset of elements, but since the elements (together with the list object itself) are probably descendants, creating an instance of the object in which this method is defined is not good enough, so how it should be of the same type of instance.
i.e.
TParentItem = Class End; TParentList = Class Items : TList<TParentItem>; Function GetSubRange(nStart,nEnd : Integer) : TParentList; End; TChildItem = Class(TParentItem) end TChildList = Class(TParentList) end List := TChildList.Create; List.LoadData; SubList := List.GetSubRange(1,3);
Implementation if GetSubRange will be something like ...
Function TParentList.GetSubRange(nStart,nEnd : Integer) : TParentList; var aContext: TRttiContext; aType: TRttiType; aInsType : TRttiInstanceType; sDebug : String; begin aContext := TRttiContext.Create; aType := aContext.GetType(self.ClassType); aInsType := aType.AsInstance; Result := aInsType.GetMethod('Create').Invoke(aInsType.MetaclassType,[]).AsType<TParentList>; sDebug := Result.ClassName;
I appreciate for some things that this may be a bit OTT, but in the project above it works and is another alternative, although I appreciate it is not a class method.
Steve childs
source share