【问题标题】:C++/CLI - Convert System::Object to ContextMenuStripC++/CLI - 将 System::Object 转换为 ContextMenuStrip
【发布时间】:2018-05-16 17:01:45
【问题描述】:

我正在处理一段遗留代码,我正在尝试更新一些界面。我不精通 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】:

来自 Hans Passant 发布的链接:

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

所以你应该使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-26
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多