How to deserialize byte[] into generic object to be cast at method call

你。 提交于 2019-12-04 05:56:51

The type you want to deserialize must be known at compile time.. So your method can be like:

private T Deserialize<T>(byte[] param)
{
    using (MemoryStream ms = new MemoryStream(param))
    {
        IFormatter br = new BinaryFormatter();
        return (T)br.Deserialize(ms);
    }
}

Now you can use it like

var myclass = Deserialize<MyClass>(buf);

You need to simply utilize the type parameter of your class.

By trying to dynamically do a GetType or a cast, you're forcing a runtime evaluation, rather than using generics to create a compile-time referenced version.

The type parameter will compile a separate version of your class that is strongly typed for every parameter type T that is encounted by the compiler. So T is actually a placeholder for a strong reference.

obj = (br.Deserialize(ms) as T);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!