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

前端 未结 2 1545
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 19:26

I am working on an object encryption class. I have everything worked out but I want to be able to encrypt/decrypt any object type with one deserialize method. As of now the only

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-14 19:59

    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);
    

提交回复
热议问题