简体   繁体   中英

How can I turn a list of properties into a stringlist?

I have a component with a lot of properties, many of which are types.

For example:

BackgroundStyle = [bsSolid, bsGradient, bsNone]

BorderStyle = [bsNone, bsSingle, bsWide]

I am building a form to allow the user to configure these properties at runtime and I would like to populate some dropdown lists dynamically, rather than having to type all of them in by hand.

Is this possible? Thanks!

Use RTTI for that. Specifically, look at the GetPropInfo() and GetEnumName() functions in the TypInfo unit.

Remy is on the ball with this one. Lately I just happen to do something similar and a bit of refactoring (within a text editor, so you mileage may vary with the complier):

class function TEnumerationRoutines.TitleCaseDescriptionFromOptions<T>: TStrings;
var
  LRttiContext : TRttiContext;
  LRttiEnumerationType: TRttiEnumerationType;
  LTypeInfo : Pointer;
  LPTypeInfo : PTypeInfo;
  lp: Integer;
begin
  LTypeInfo := TypeInfo(T);

  LPTypeInfo := PTypeInfo(LTypeInfo);
  if LPTypeInfo^.Kind <> tkEnumeration then
    raise Exception.Create('Type is not an enum');

  Result := TStringList.Create;

  LRttiEnumerationType := LRttiContext.GetType(LTypeInfo) as TRttiEnumerationType;

  for lp := LRttiEnumerationType.MinValue to LRttiEnumerationType.MaxValue do
    Result.Add(GetEnumName(LTypeInfo, Ord(lp)));
end;

and call it with:

MyStrings := TEnumerationRoutines.TitleCaseDescriptionFromOptions<BackgroundStyle>;

or

MyStrings := TEnumerationRoutines.TitleCaseDescriptionFromOptions<BorderStyle>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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