[英].Net XML Serializer and matrix
我在C#項目中包裝並使用了C ++ / CLI代碼。 我在C ++ / CLI代碼中有一個類,其中包含一個聲明如下的矩陣:
array<double, 2>^ S_to_Box_Matrix;
S_to_Box_Matrix = gcnew array<double, 2>(4, 4);
似乎此變量不可序列化。 如何使其可序列化? 如果不可能,那么如何從序列化中排除它(哪個C ++ / CLI關鍵字以及要導入的庫)謝謝。
XmlSerializer
不支持2d數組。 解決此問題的最直接方法是按如下所示修改c ++ / cli類:
[XmlIgnore]
標記2d數組 [XmlArray]
標記鋸齒狀的數組屬性 例如:
#using <System.Xml.dll>
public ref class Array2DTestClass
{
public:
[System::Xml::Serialization::XmlIgnore]
array<double, 2> ^S_to_Box_Matrix;
[System::Xml::Serialization::XmlArray("S_to_Box_Matrix")]
property array<array<double> ^>^ S_to_Box_Matrix_Serializable {
array<array<double> ^>^ get();
System::Void set(array<array<double> ^>^ value);
}
};
與實施
array<array<double> ^>^ Array2DTestClass::S_to_Box_Matrix_Serializable::get() {
return ArrayExtensions::ToJaggedArray(this->S_to_Box_Matrix);
}
System::Void Array2DTestClass::S_to_Box_Matrix_Serializable::set(array<array<double> ^>^ value) {
this->S_to_Box_Matrix = ArrayExtensions::To2DArray(value);
}
使用輔助方法:
public ref class ArrayExtensions abstract sealed {
public:
generic<typename T> static array<array<T>^> ^ToJaggedArray(array<T, 2> ^input)
{
if (input == nullptr)
return nullptr;
int nRow = input->GetLength(0);
int nCol = input->GetLength(1);
array<array<T>^> ^output = gcnew array<array<T>^>(nRow);
for (int iRow = 0; iRow < nRow; iRow++)
{
output[iRow] = gcnew array<T>(nCol);
for (int iCol = 0; iCol < nCol; iCol++)
output[iRow][iCol] = input[iRow, iCol];
}
return output;
}
generic<typename T> static array<T, 2> ^To2DArray(array<array<T> ^>^input)
{
if (input == nullptr)
return nullptr;
int nRow = input->Length;
int nCol = 0;
for (int iRow = 0; iRow < nRow; iRow++)
if (input[iRow] != nullptr)
nCol = Math::Max(nCol, input[iRow]->Length);
array<T, 2> ^ output = gcnew array<T, 2>(nRow, nCol);
for (int iRow = 0; iRow < nRow; iRow++)
if (input[iRow] != nullptr)
for (int iCol = 0; iCol < input[iRow]->Length; iCol++)
output[iRow, iCol] = input[iRow][iCol];
return output;
}
};
這樣做,我得到的XML如下所示:
<Array2DTestClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <S_to_Box_Matrix> <ArrayOfDouble> <double>0</double> <double>1</double> <double>2</double> </ArrayOfDouble> <ArrayOfDouble> <double>3</double> <double>4</double> <double>5</double> </ArrayOfDouble> </S_to_Box_Matrix> </Array2DTestClass>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.