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

标签 delphi exception casting variant

在 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/

相关文章:

delphi - 如何禁用 UNSAFE_CAST 选项?

c++ - 当前形式的 `std::exception` 是多余的吗?

java - CompletableFuture 句柄和completeExceptionally 不能一起工作吗?

c - 在数据类型之间切换

delphi - 在 FireMonkey 中更改 TMemo 的字体和背景颜色

delphi - 当子窗体在 Delphi 中可见时,如何防止父窗体中的操作执行

delphi - 当使用 --no-config 参数调用时,dcc32.exe 编译器会使用项目构建配置文件吗?

PHP(或其他): Strategy to deal with exceptions that "cannot occur"

C# 泛型 : cast generic type to value type

c# - 我真的只是将字符串数据类型放入 IEnumerable<int>