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

时间:2018-05-16 17:01:45

标签: c++-cli

我正在制作一段遗留代码&我正在尝试更新一些界面。我不擅长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中完成?

1 个答案:

答案 0 :(得分:1)

通过汉斯·帕桑特(Hans Passant)发布的链接:

  

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

因此您应该使用:

Windows::Forms::ContextMenuStrip ^menu = safe_cast<Windows::Forms::ContextMenuStrip^>(sender);