将System :: object转换为字符串数组

时间:2012-10-28 06:25:09

标签: string c++-cli

我需要在后台工作人员的工作中返回四维字符串数组,后者通过串口接收数据。

在后台工作人员中:

    array<String^>^ Received = gcnew array<String^>(4);
    backgroundWorker1->ReportProgress(10,Received);

报告进度中:

private: System::Void backgroundWorker1_ProgressChanged(System::Object^ sender,   System::ComponentModel::ProgressChangedEventArgs^  e)
{
    array<String^>^ Received2 = gcnew array<String^>(4);
    Received2 =(e->UserState);
}

我得到了:

  

错误C2440:'=':无法从'System :: Object ^'转换为'cli :: array“

这并不奇怪,但如何转换并将UserState分配给string array

1 个答案:

答案 0 :(得分:0)

您需要将对象句柄强制转换为数组句柄,然后检查nullptr以查看强制转换是否成功,例如:

array<String^>^ Received2 = dynamic_cast<array<String^>^>(e->UserState);
if (Received2 != nullptr)
{
    // Cast was successful, safe to use Received2.
}
else
{
    // Cast failed, do not use Received2.
}