不同命名空间下名称和结构相同的类相互序列化与反序列化

首先建2个类,它们的命名空间不一样,但类名和结构相同:

代码
   
     
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Domain1 {
public class Person {
public int Id { get ; set ; }
public string Name { get ; set ; }
}
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Domain2 {
public class Person {
public int Id { get ; set ; }
public string Name { get ; set ; }
}
}
然后在Program.cs里对Domain1.Person进行序列化:

代码
   
     
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using Domain1;

namespace ConsoleApplication1 {
class Program {
static void Main( string [] args) {
Person person
= new Person { Id = 1 , Name = " Who " };
XmlSerializer serializer
= new XmlSerializer( typeof (Person));
using (FileStream fs = new FileStream( " d:\\person.xml " , FileMode.Create)) {
serializer.Serialize(fs, person);
}

Console.WriteLine(
" ID:{0} Name:{1} " , person.Id, person.Name);
Console.Read();
}
}
}
运行程序,会在D盘生成Domain1.Person对象的XML文件person.xml,

然后修改下程序,用Domain2.Person对D:\person.xml进行反序列化:

代码
   
     
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using Domain2;

namespace ConsoleApplication1 {
class Program {
static void Main( string [] args) {
Person person
= null ;
XmlSerializer serializer
= new XmlSerializer( typeof (Person));
using (FileStream fs = new FileStream( " d:\\person.xml " , FileMode.Open)) {
person
= serializer.Deserialize(fs) as Person;
}

Console.WriteLine(
" ID:{0} Name:{1} " , person.Id, person.Name);
Console.Read();
}
}
}
运行程序,成功反序列化。

如果在Domain1.Person类中增加或者减少属性,用Domain2.Person同样可以反序列化。

你可能感兴趣的:(反序列化)