问题描述
我有一个托管类,想在<div class="modal" id="createMessageModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
@using (Html.BeginForm("Dashboard","App",null,FormMethod.Post,new { @id = "frmSendMessage",@name = "frmSendMessage" }))
{
<div class="modal-header">
<h5 class="modal-title">Send Message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table>
<tbody>
<tr>
<th style="padding-bottom:15px">From:</th>
@Html.HiddenFor(model => model.messageSenderID)
<td style="padding-bottom:15px;">@ViewBag.Name</td>
</tr>
<tr>
<th style="padding-bottom:15px">To:</th>
<td style="width:100% !important; padding-bottom: 15px;">
@Html.DropDownListFor(model => model.messageRecipientID,Model.messageRecipientsDropdown,"Select A Recipient",new { @id = "recipient",@name = "recipient",@class = "form-control" })
@Html.ValidationMessageFor(model => model.messageRecipientID,"",new { @class = "text-danger" })
</td>
</tr>
<tr>
<th>Subject:</th>
<td style="width:100% !important">@Html.TextBoxFor(model => model.messageSubject,new { @class = "form-control",@name = "messageSubject",@id = "messageSubject" })</td>
<td>@Html.ValidationMessageFor(model => model.messageSubject,new { @class = "text-danger" })</td>
</tr>
</tbody>
</table>
<br />
@Html.TextAreaFor(model => model.messageBody,new { rows = "15",style = "resize:none; min-width:100%;",id = "messageBody",name = "messageBody" })
@Html.ValidationMessageFor(model => model.messageBody,new { @class = "text-danger" })
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Send Message</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
}
</div>
</div>
</div>
方法中设置本机类。
$(document).ready(function() {
$("#frmSendMessage").submit(function() {
Recipient = $("input[name='recipient']").val();
MessageSubject = $("input[name='messageSubject']").val();
MessageBody = $("input[name='messageBody']").val();
return false;
})
});
但是,运行create()
时会删除ref class ManagedClass {
private:
NativeClass* ptr = nullptr;
public:
void create()
{
NativeClass nativeClass;
nativeClass.set(0);
this->ptr = &nativeClass;
}
};
。因此nativeClass
为空。如何使局部变量create()
不被删除?
解决方法
当定义了局部变量的函数返回时,局部变量将不复存在,并且任何记住的指向该局部变量的指针都将变为无效。 C ++ / CLI与非托管C ++没什么不同。
要创建在create
调用之后仍然存在的对象,请动态分配该对象并使用ptr = new NativeClass();
保存指向它的指针(然后,在不再需要时不要忘记delete ptr;
)