如何在C++ FireMonkey TStringGrid::OnDrawColumnCell事件中访问const TValue&的布尔值?
在FMX TStringGrid::OnDrawColumnCell中读取const TValue的布尔值
问题场景
回调函数定义如下:
void __fastcall TMainForm::SegmentStringGridDrawColumnCell(TObject *Sender, TCanvas * const Canvas, TColumn * const Column, const TRectF &Bounds, const int Row, const TValue &Value, const TGridDrawStates State)
遇到两个问题:
- 直接调用
Value.AsBoolean()时编译报错:
[bcc64x Error] main.cpp(235): 'this' argument to member function 'AsBoolean' has type 'const System::Rtti::TValue', but function is not marked const
- 将const TValue复制到非const变量后调用AsBoolean,运行时抛出异常:
exception class EInvalidCast with message 'Invalid class typecast'
复制代码如下:
TValue MyValue; #ifndef __clang__ MyValue = TValue::_op_Implicit(Value); #else MyValue = TValue::From(Value); #endif bool myVal = MyValue.AsBoolean();
解决方案
方法1:使用TValue::GetValue<T>()(推荐)
GetValue<T>()是const成员函数,可直接在const TValue对象上调用,能安全获取指定类型的值,同时自动处理类型兼容转换:
bool myVal = false; if (Value.IsType<bool>()) { // 先检查类型,避免转换异常 myVal = Value.GetValue<bool>(); }
方法2:基于类型判断直接访问数据
如果需要更底层的处理,可以先判断类型后直接访问TValue存储的数据:
bool myVal = false; if (Value.TypeKind == tkBoolean) { myVal = *static_cast<const bool*>(Value.Data); }
异常原因说明
之前复制后抛出EInvalidCast,大概率是原TValue存储的并非布尔类型(比如实际是字符串或其他类型),或者转换方式不符合类型存储规则。先检查类型再转换,能从根源避免这类问题。
内容的提问来源于stack exchange,提问作者Barry Andrews
相关产品推荐
相关产品推荐

