C ++ / CLI - 将System :: Object转换为ContextMenuStrip

问题描述 投票:0回答:1

我正在研究一段遗留代码,我正在尝试更新一些接口。我不擅长C ++ / CLI,C ++ / CLI的文档充其量只是稀疏的。我尽力将C#文档转换为C ++ / CLI,但它并不总是有效。

我想将System :: Object转换为ContextMenuStrip。

示例代码是:

System::Void Form1::unzoomToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e)
{

    System::Windows::Forms::ContextMenuStrip ^menu = sender;
    //a value of type "System::Object ^" cannot be used to initialize and entity of type "System::Windows::Forms::ContextMenuStrip ^"

    //Other code here
}

这是如何在C ++ / CLI中完成的?

c++-cli
1个回答
1
投票

来自Hans Passant发布的链接:

向下转换是从基类到从基类派生的类的转换。只有在运行时寻址的对象实际处理派生类对象时,向下转换才是安全的。与static_cast不同,safe_cast执行动态检查,如果转换失败则抛出InvalidCastException。

所以你应该使用:

Windows::Forms::ContextMenuStrip ^menu = safe_cast<Windows::Forms::ContextMenuStrip^>(sender);
© www.soinside.com 2019 - 2024. All rights reserved.