如何将 String 转换为 TValue?

How to cast String to TValue?

此代码在最后一行 prop->SetValue(control, value) 抛出 Invalid typecast

我想我投错了 "MyString"。正确的方法是什么?

for (int i = 0; i < MyForm->ControlCount; i++) {
    TControl *control = MyForm->Controls[i];
    if (control->Name == "MyTEdit") {
        TRttiContext ctx;
        TRttiType *type = ctx.GetType(control->ClassInfo());
        TRttiProperty *prop = type->GetProperty(L"Text");
        TValue value = TValue::From("MyString");
        prop->SetValue(control, value);
    }
}

它应该遍历 MyForm 中的所有控件,直到找到 TEditMyTEditName,并将框中的文本更改为MyString.

我的代码基于 答案。不幸的是,它没有提供将 String 文字转换为 TValue 的示例,所以我不知所措。

更新

看完问题的答案后,我把TValue value = TValue::From("MyString");改为:

String myString = "MyString";
TValue value = TValue::From<UnicodeString>(myString);

现在我得到以下错误:

[ilink32 Error] Error: Unresolved external 'System::Rtti::TValue __fastcall System::Rtti::TValue::From<System::UnicodeString>(System::UnicodeString)' referenced from UNIT1.OBJ

我已将其包含在 Unit1.cpp 的顶部:

#pragma explicit_rtti
#include <System.Rtti.hpp>

所以我不明白为什么会这样说。

更新 2

当我从 32 位切换到 64 位时,问题消失了。

TValue::From<T>() 是一个 Delphi 泛型方法,并且在 C++ 中使用泛型有记录的链接器问题:

How to Handle Delphi Generics in C++.

请尝试使用 using the assignment operator=,因为 TValue 具有 UnicodeString 的赋值运算符:

String myString = "MyString";
TValue value;
value = myString;
TValue value;
value = String("MyString");