You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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)

遇到两个问题:

  1. 直接调用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

  1. 将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:52:02