如何使用BinaryFormatter(C#)将类反序列化为不同的类(在新的命名空间中)

Dio*_*ung 0 c# serialization deserialization

我有一个User属于Authentication命名空间的类,如下所示:

namespace Authentication {
    public class User 
    {
       public string Name {get;set;}    
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用BinaryFormatter将类User的对象序列化为byte []并将其存储在数据库中.

User usr = new User();
usr.Name = "myself";
var usrValue = convertObjectToByteArr(usr);
//then store usrValue into db.
Run Code Online (Sandbox Code Playgroud)

一段时间后,类User具有新属性并移动到新命名空间: Authentication.Organization

namespace Authentication.Organization{
    public class User 
    {
        public string Name {get;set;}

        public int Age {get;set;}
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题:如何将previous用户对象反序列化为current用户?

我会遇到异常:{"Unable to load type Authentication.User required for deserialization."}当我尝试反序列化时:

byte[] prevUsrValue= (byte[])helper.getPreviousUserValue();//read from database

User previousUser = convertByteArrToObject(prevUsrValue) as User;
Run Code Online (Sandbox Code Playgroud)

仅供参考,我正在使用这些方法进行序列化和反序列化:

//serialization
public static byte[] convertObjectToByteArr(object o)
{
    if (o != null)
    {
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        binaryFormatter.Serialize(memoryStream, o);
        return memoryStream.ToArray();
    }
    return null;
}

//de-serialization
public static object convertByteArrToObject(byte[] b)
{
    if (b != null && b.Length > 0)
    {
        System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(b);
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        memoryStream.Position = 0;
        return binaryFormatter.Deserialize(memoryStream);

    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*anu 5

不要将二进制序列化对象存储在数据库中.使用您选择的ORM(EF,Linq2SQL,NHibernate等)将用户的属性序列化为表.

二进制对象序列化到数据库中是非常糟糕的.数据库是长寿和可查询的.你是一举否定的:你的长期数据可以通过你现在拥有的非常具体的代码来反序列化(20年后,有人必须运行C#v.4.5来对今天存储的对象进行去序列化)和二进制序列化对象对于数据库而言,它只是一个不透明的blob,不可思议且无法搜索.

不要这样做.