[英]How to convert set of integer to comma separated string in Delphi?
private const
CA_2_4_RECOMMENDED_CHANNELS = [1, 5, 6, 9, 11, 13];
I can use the "for" loop, but how can I use some generics to get a comma separated string like '1, 5, 6, 9, 11, 13' without any loops?我可以使用“for”循环,但我如何使用一些 generics 来获得一个逗号分隔的字符串,如 '1, 5, 6, 9, 11, 13' 而没有任何循环?
The simplest way uses the TStringList class from the System.Classes unit:最简单的方法是使用 System.Classes 单元中的 TStringList class:
const
CA_2_4_RECOMMENDED_CHANNELS = [1, 5, 6, 9, 11, 13];
var
c: integer;
sl: TStringList;
begin
sl := TStringList.Create;
try
for c in CA_2_4_RECOMMENDED_CHANNELS do
sl.Add(c.ToString);
writeln(sl.CommaText);
finally
sl.Free;
end;
end;
But even with this solution, a For-Each loop is required to fill the StringList.但即使使用此解决方案,也需要一个 For-Each 循环来填充 StringList。 A solution where each element must not be touched does not exist from my point of view.从我的角度来看,不存在不能触及每个元素的解决方案。
You can do this with RTTI, for example.例如,您可以使用 RTTI 执行此操作。
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.Rtti;
type
TMySet=set of byte;
var
m: TMySet;
v: TValue;
begin
try
m := [1, 5, 6, 9, 11, 13];
v := TValue.From<TMySet>(m);
writeln(v.ToString());
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.