gpt4 book ai didi

delphi - 测试强制转换 OleVariant 是否会引发异常(不引发异常)

转载 作者:行者123 更新时间:2023-12-02 06:16:50 31 4
gpt4 key购买 nike

在 Delphi 中,我想确定是否可以将特定的 OleVariant 转换为特定的数据类型如果不能则不引发异常。异常不适用于程序流程,对吗?

我想要的是这样的,其中 Type 可以是 OleVariant 支持的任何内容:

if TryVarAsType(variant, value) then ...

想要的是

try
value := Type(variant);
// case where the variant could be converted to a Type
except
// case where the variant could not be converted to a Type
end;

变体无法转换为 bool 值的情况只是经常发生的正常情况,并不表示任何类型的错误。

最佳答案

您可以使用 VariantChangeTypeEx 构造这样的函数功能。

uses
VarUtils,
Variants;

function TryVarAsType( AVariant : OleVariant; const AVarType: TVarType ) :Boolean;
var
SourceType: TVarType;
begin
SourceType:=TVarData(AVariant).VType;
//the types are ole compatible
if (AVarType and varTypeMask < varInt64) and (SourceType and varTypeMask < varInt64) then
Result:=
(SourceType=AVarType) or
(VariantChangeTypeEx(TVarData(AVariant), TVarData(AVariant), VAR_LOCALE_USER_DEFAULT, 0, AVarType)=VAR_OK)
else
Result:=False; //Here you must process the variant pascal types like varString
end;

像这样使用

TryVarAsType('1',varInteger);
TryVarAsType('s',varInteger)

这仅适用于 ole 兼容的变体类型

  varEmpty    = $0000; { vt_empty        0 }
varNull = $0001; { vt_null 1 }
varSmallint = $0002; { vt_i2 2 }
varInteger = $0003; { vt_i4 3 }
varSingle = $0004; { vt_r4 4 }
varDouble = $0005; { vt_r8 5 }
varCurrency = $0006; { vt_cy 6 }
varDate = $0007; { vt_date 7 }
varOleStr = $0008; { vt_bstr 8 }
varDispatch = $0009; { vt_dispatch 9 }
varError = $000A; { vt_error 10 }
varBoolean = $000B; { vt_bool 11 }
varVariant = $000C; { vt_variant 12 }
varUnknown = $000D; { vt_unknown 13 }
varShortInt = $0010; { vt_i1 16 }
varByte = $0011; { vt_ui1 17 }
varWord = $0012; { vt_ui2 18 }
varLongWord = $0013; { vt_ui4 19 }
varInt64 = $0014; { vt_i8 20 }

对于其他类型(pascal 变体),例如 varStringvarAny,您必须检查源和目标 TVarType 并编写自己的测试用例.

更新

正如@David 指出的,区域设置可以为相同的值产生不同的结果,因此您必须将此答案视为构建您自己的函数的初始步骤或提示,并且您必须意识到在建议的功能。

关于delphi - 测试强制转换 OleVariant 是否会引发异常(不引发异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5183794/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com