xmlserializer를 사용하여 정수 배열을 직렬화합니다
-
23-08-2019 - |
문제
XMLSerializer를 통해 여러 차원의 정수 배열을 직렬화하려고하는 동안 문제가 발생합니다. 히치없이 다른 모든 데이터 (부울, 문자열, 색상 등)를 직렬화 할 수 있습니다. 나는 또한 많은 사람들이 XMLSerializer가 정수의 정수를 기본적으로 처리 할 것이라고 주장하는 것을 보았습니다. 다중 차원 배열에 관한 제한이 있습니까? 아니면 다른 일이 일어나고 있습니까?
관련 코드는 다음과 같습니다.
int[,,] scoredata = scores; // Populated with data elsewhere
filename = Path.Combine(container.Path, "scoredata.sav");
stream = File.Open(filename, FileMode.Create);
serializer = new XmlSerializer(typeof(int[,,]));
serializer.Serialize(stream, scoredata); // This line throws the exception.
stream.Close();
내가받는 예외는 "system.invalidoperationException '유형의 처리되지 않은 예외입니다. XML 문서를 생성하는 오류가 발생했습니다."
또한이 배열을 구조물에서 멤버 변수로 사용하려고 시도했지만 (다른 모든 플레이어 데이터가 저장되는 곳) 그런 식으로 작업을 수행 할 때도 동일한 예외가 발생하여 간단한 구문 오류 또는 그와 비슷한 것.
단일 차원 배열을 통해 직렬화되도록 코드를 재구성해야합니까, 아니면 간과하고있는 것이 있습니까?
미리 감사드립니다!
해결책
내부 예측을 읽으십시오.
- 유형 'sombertype'를 반영하는 오류가있었습니다. 'system.int32 [,,]'유형의 멤버 'sombertype.data'를 일련의 일련화 할 수 없으며 자세한 내용은 내부 예외를 참조하십시오.
- system.int32 [,,]의 객체를 직렬화 할 수 없습니다. 다차원 배열은 지원되지 않습니다.
따라서 아니오 : 다차원 배열은 단순히 지원되지 않습니다. 단일 차원 배열로 그것을 깎아야 할 수도 있습니다 ... 번역을 수행하는 별도의 속성을 가질 수 있습니다.
[XmlIgnore]
public int[, ,] Data { get; set; }
[XmlElement("Data"), Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public int[] DataDto
{
get { /* flatten from Data */ }
set { /* expand into Data */ }
}
다른 팁
다차원 배열을 평평하게하고 확장하기 위해 Marc의 Get에 들어가야하는지 알아내는 데 시간이 걸렸습니다.
다음은 2D 어레이에 대한 내 솔루션입니다.
제 경우에는 컴파일 시간에 치수 중 하나가 4라는 것을 알고 있으므로 배열 치수를 저장할 필요가 없었습니다.
[XmlIgnore]
public int[,] Readings { get; set; }
[XmlArray("Readings")]
public int[] ReadingsDto {
get { return Flatten(Readings); }
set { Readings = Expand(value, 4); }
}
public static T[] Flatten<T>(T[,] arr)
{
int rows0 = arr.GetLength(0);
int rows1 = arr.GetLength(1);
T[] arrFlattened = new T[rows0 * rows1];
for (int j = 0; j < rows1; j++)
{
for (int i = 0; i < rows0; i++)
{
var test = arr[i, j];
arrFlattened[i + j * rows0] = arr[i, j];
}
}
return arrFlattened;
}
public static T[,] Expand<T>(T[] arr, int rows0)
{
int length = arr.GetLength(0);
int rows1 = length / rows0;
T[,] arrExpanded = new T[rows0, rows1];
for (int j = 0; j < rows1; j++)
{
for (int i = 0; i < rows0; i++)
{
arrExpanded[i, j] = arr[i + j * rows0];
}
}
return arrExpanded;
}