问题
If I have a class/interface pair defined in AssemblyA
under namespace AssemblyA.Entities
:
public IEntity
{
string Name { get; set; }
}
[Serializable]
public Entity : IEntity
{
public string Name { get; set; }
}
And I serialize it to XML using XmlSerializer
:
var myEntities = new List<IEntity>();
// myEntities is populated somehow
var data = XmlSerializationManager.Serialize(myEntities);
// 'data' gets saved to disk somewhere as a file
Then, if I duplicate the code/namespaces into AssemblyB
so that I have namespace AssemblyA.Entities
and the exact same code:
public IEntity
{
string Name { get; set; }
}
[Serializable]
public Entity : IEntity
{
public string Name { get; set; }
}
If I attempt to deserialize the previously serialized XML, will I get back AssemblyB
's list of AssemblyA.Entities.IEntity
? Or will it fail?
At what point does the serializer stop caring about what it's deserializing to? Can the assembly differ? Can the namespaces differ? Do the type names matter so long as the properties are named the same?
回答1:
This will work. You will get AssembyB entity.
This is essentially how Web services work when the client would scaffold classes based on information in the wsdl, the client would then deserialise the data from the soap message into these scaffolded classes.
来源:https://stackoverflow.com/questions/26368990/deserialize-matching-types-from-different-assemblies