问题描述
服务器代码具有允许的“名称”与相应的 Delphi 类型的映射,我希望将“值”部分(以字符串格式接收)转换为相应的 TValue 变量,该变量在处理中进一步使用链。
除了设置一个大的 if/else 语句来测试“名称”的映射类型之外,RTTI 有什么方法可以提供帮助。我可以使用 TRTTIContext 的 FindType 方法获取映射类型的 PTypeInfo,并且可以看到一些带有 PTypeInfo 参数的 TValue 方法。
在此阶段,我查看了 TValue.Cast 和 TValue.Make,但它们在将“10”转换为整数时失败。
我是否只是回到 if/else 方法并处理我需要处理的类型?
解决方法
TValue
表示编译器支持的相同隐式强制转换。例如,Int16<->Integer
,但不是 String<->Integer
。那些善意的转换,你必须自己做
我可能会这样做:
type
ConvFunc = function(const Value: String): TValue;
function ConvToInt(const Value: String): TValue;
begin
Result := StrToInt(Value);
end;
// other conversion functions as needed...
var
Dict: TDictionary<String,ConvFunc>;
Func: ConvFunc;
Value: TValue;
begin
Dict := TDictionary<String,ConvFunc>.Create;
Dict.Add('name',@ConvToInt);
// add other entries as needed...
...
if not Dict.TryGetValue('NameToFind',Func) then
begin
// name is not supported...
end else
begin
try
Value := Func('InputToConvert');
// use Value as needed...
except
// input is not supported...
end;
end;
...
Dict.Free;
end;