2013-06-21 1 views
2

의 여러 유형을 역 직렬화 우리가 2 개 (또는 그 이상) 클래스 :직렬화와 객체

class numOne 
{ 
    string name; 
    int age; 
} 
class numTwo 
{ 
    Bitmap pImage; 
} 

그리고 난이 클래스의 인스턴스를 포함하는 ArrayList를이 : 우리가있을 때

ArrayList list = new ArrayList(); 
numOne n1 = new numOne(){ name="sth", age =18 }; 
numTwo n2 = new numTwo(){ pImage = new Bitmap("FileAddress") }; 
list.Add(n1); 
list.Add(n2); 

나는 알고있다 클래스의 한 종류, 내가 serialize하고 BinaryFormatter 함께 목록 (<> 같은) 개체를 deserialize 할 수 있습니다. 하지만 ArrayLists 및 this와 같은 일부 복잡한 objectes에 대해이 작업을 어떻게 사용할 수 있는지 알 수 없습니다. 어떻게해야합니까?

고맙습니다 ...

+0

'DataContractSerializer'에는 알려진 유형의 IEnumerable 을 목록에 포함하는 [생성자 오버로드] (http://msdn.microsoft.com/en-us/library/aa344259.aspx)가 있습니다. 배열리스트에있는 어떤 타입이라도 사용할 수있게하려면 이렇게 할 수 있습니다 :'new DataContractSerializer (typeof (ArrayList), list.Select (x => x.GetType()))'. –

+0

제쳐두고, 왜 유형을 목록에 혼합하고 있습니까? 그것은 코드 냄새입니다. 공통 기본 클래스에서 확장하지 않는 한'List '을 사용할 수 있습니다. –

답변

2

이 기능이 작동합니까?

[Serializable] 
     class numOne 
     { 
      public string name; 
      public int age; 
     } 
     [Serializable] 
     class numTwo 
     { 
      public string rg; 
     } 
     private void Button_Click_1(object sender, RoutedEventArgs e) 
     { 
//Serialization 
      using (var fs = new FileStream("DataFile.dat", FileMode.Create)) 
      { 
       var listToBeSerialized = new ArrayList(){     
       new numOne() { name = "sth", age = 18 }, 
       new numTwo() { rg = "FileAddress" } 
      }; 
       new BinaryFormatter().Serialize(fs, listToBeSerialized); 
      } 

//Deserialization 
      using (var fs = new FileStream("DataFile.dat", FileMode.Open)) 
      { 
       var deserializedList = (ArrayList)new BinaryFormatter().Deserialize(fs); 
      } 
     } 

비트 맵 클래스의 경우 직렬화 가능 여부를 확인해야합니다.

+0

나는 당신의 해결책을 고쳤다 .-) 감사했다. –

+0

환영 : –

관련 문제