简短的免费原生对象

时间:2012-12-10 03:57:21

标签: .net c++-cli

如果我有多个本机类型变量:

EmpNameC =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox38->Text).ToPointer();
PyrllC =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox31->Text).ToPointer();
DtbrthC=( wchar_t *)Marshal::StringToHGlobalUni(this->textBox37->Text).ToPointer();
PlcBrthC=( wchar_t *)Marshal::StringToHGlobalUni(this->textBox36->Text).ToPointer();
CIDC    =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox35->Text).ToPointer();
ContNoC=( wchar_t *)Marshal::StringToHGlobalUni(this->textBox34->Text).ToPointer();
JndtC   =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox33->Text).ToPointer();
PostnC  =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox32->Text).ToPointer();
DeptC   =( wchar_t *)Marshal::StringToHGlobalUni(this->comboBox4->Text).ToPointer();
AnnLvC  =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox9->Text).ToPointer();
EmrgLvC=( wchar_t *)Marshal::StringToHGlobalUni(this->textBox30->Text).ToPointer();
IrrC=( wchar_t *)Marshal::StringToHGlobalUni(this->comboBox1->SelectedItem->ToString()).ToPointer();
HmTwnC  =( wchar_t *)Marshal::StringToHGlobalUni(this->textBox25->Text).ToPointer();

我必须释放所有人,比如:

Marshal::FreeHGlobal((IntPtr)EmpNameC);      
Marshal::FreeHGlobal((IntPtr)DtbrthC);
Marshal::FreeHGlobal((IntPtr)PlcBrthC);
Marshal::FreeHGlobal((IntPtr)CIDC);
Marshal::FreeHGlobal((IntPtr)ContNoC);
Marshal::FreeHGlobal((IntPtr)JndtC);
Marshal::FreeHGlobal((IntPtr)PostnC);
Marshal::FreeHGlobal((IntPtr)DeptC);
Marshal::FreeHGlobal((IntPtr)AnnLvC);
Marshal::FreeHGlobal((IntPtr)EmrgLvC);
Marshal::FreeHGlobal((IntPtr)IrrC);
Marshal::FreeHGlobal((IntPtr)HmTwnC);

有没有更短的方法可以用来释放所有本机对象而不是每个对象执行一次?

1 个答案:

答案 0 :(得分:2)

您可以使用包含队列的专用结构来管理它。

每次分配本机对象时,都会将其推入队列,最后将它们全部释放到循环中。