测试强制转换 OleVariant 是否会引发异常(不引发异常)
在 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;
变体无法转换为布尔值的情况只是正常情况,定期发生,并不表示有任何类型的错误。
In Delphi I want to determine whether a particular OleVariant can be cast to a particular data type without raising an exception if it can't. Exceptions are not for program flow, right?
What I want is something like this, where Type could be anything supported by an OleVariant:
if TryVarAsType(variant, value) then ...
What I don't want is
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;
The case where the variant could not be converted to a Boolean is just a normal case that occurs regularly and doesn't indicate any kind of error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
VariantChangeTypeEx
函数构造此类函数。并像这样使用,
这仅适用于
其他类型(pascal 变体)的 ole 兼容变体类型,例如
varString
、varAny
您必须检查源和目标TVarType
并编写您自己的测试用例。更新
正如@David 指出的,区域设置可以为相同的值产生不同的结果,因此您必须将此答案视为构建您自己的函数的初始步骤或提示,并且您必须了解区域设置建议的功能中引起的设置问题。
you can construct such function using the
VariantChangeTypeEx
function.and use like this
this will work with only with ole compatible Variant types
for the another types (pascal variants) like
varString
,varAny
you must check the source and destinationTVarType
and write your own test cases.UPDATE
As @David point me out, the locale settings can produce different results for the same values, so you must consider this answer just as initial step or tip to construct your own function and you must aware of locale settings issues caused in the proposed function.
我不知道内置支持允许动态转换检查失败并出现错误代码而不是异常。
您可以自己手动编码,但这样做会在变体单元中产生大量无法容忍的重复代码。在这种情况下,我认为使用异常比复制依赖于实现的代码的替代方案要好。
作为 RRUZ 最巧妙答案的反例,我提供以下代码:
输出:
I'm not aware of built-in support that would allow dynamic conversion checking that failed with an error code rather than an exception.
You could hand-code it yourself but doing so would produce an intolerable amount of duplication of the code in the Variants unit. In this case I think that using exceptions is less bad than the alternative of duplicating implementation dependent code.
As a counter-example to RRUZ's most ingeneous answer, I offer the following code:
Output: