일반 목록을 역직렬화하면 null이 반환됩니다.
-
21-08-2019 - |
문제
다음과 같이 객체를 역직렬화/역직렬화하고 있습니다.
public class myClass : ISerializable
{
public List<OType> value;
public myClass(SerializationInfo info, StreamingContext context)
{
this.value = (List<OType>)info.GetValue("value", typeof(List<OType>));
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("value", value, typeof(List<OType>));
}
}
목록에 있는 개체 하다 직렬화 가능 속성이 있습니다.직렬화할 때 오류가 발생하지 않으며 목록은 다음과 같습니다. 절대 비어 있지만 역직렬화할 때 모든 목록이 null이고 그 이유가 확실하지 않습니다.
CQ가 답변한 것으로 표시하겠습니다.사용하려는 개체를 적절하게 직렬화/역직렬화하는 작은 일회성 테스트 앱을 생성할 수 있었지만 여전히 프로덕션 코드에서 작동하도록 할 수 없는 것 같습니다. 없어.
해결책
글쎄, 목록은 항상 처음부터 비어 있습니다. myClass.value = new List<...>();
? 또한 직렬화 된 데이터를 바이너리 및 XML 형식으로 저장하여 실제로 데이터가 저장되고 있는지 확인할 수 있습니까?
또한 2.0+를 사용하는 경우 절대 직렬화를 제어 할 필요가없는 경우 iserializable을 구현할 필요가 없으며, 공공 재산으로 값을 변경할 수 있으며 자체적으로 직렬화됩니다.
편집 : 다음 사례는 나에게 일련의 직렬화와 사형화 된 것으로 보인다. 나는이 질문을 전체적으로 오해하고 있다면이 결과를 게시하고있다.
불쾌한 테스트 코드를 무시하면 이것이 약간 도움이되기를 바랍니다.
[Serializable]
public class OType
{
public int SomeIdentifier { get; set; }
public string SomeData { get; set; }
public override string ToString()
{
return string.Format("{0}: {1}", SomeIdentifier, SomeData);
}
}
[Serializable]
public class MyClass : ISerializable
{
public List<OType> Value;
public MyClass() { }
public MyClass(SerializationInfo info, StreamingContext context)
{
this.Value = (List<OType>)info.GetValue("value", typeof(List<OType>));
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("value", Value, typeof(List<OType>));
}
}
...
var x = new MyClass();
x.Value = new OType[] { new OType { SomeIdentifier = 1, SomeData = "Hello" }, new OType { SomeIdentifier = 2, SomeData = "World" } }.ToList();
var xSerialized = serialize(x);
Console.WriteLine("Serialized object is {0}bytes", xSerialized.Length);
var xDeserialized = deserialize<MyClass>(xSerialized);
Console.WriteLine("{0} {1}", xDeserialized.Value[0], xDeserialized.Value[1]);
출력을 잊어 버렸습니다 ..
직렬화 된 객체는 754 바이트입니다
1 : 안녕하세요 2 : 세상
제휴하지 않습니다 StackOverflow