Deserialize generic type : Generic Type « Generics « C# / C Sharp






Deserialize generic type

Deserialize generic type

    using System;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;

    public class Test{
        public static void Main(string [] args){
            BinaryFormatter binary=new BinaryFormatter();
            FileStream file= new FileStream("test.dat", FileMode.OpenOrCreate);

            MyGenericClass<int> obj1=(MyGenericClass<int>)
            binary.Deserialize(file);
            Console.WriteLine(obj1.GetValue());
        }
    }

    [Serializable] 
    public class MyGenericClass<T> {
        public MyGenericClass(T init) {
            fielda=init;
        }

        public void GetObjectData(SerializationInfo info,StreamingContext ctx) {
            info.AddValue("fielda", fielda, typeof(T));
        }

        private MyGenericClass(SerializationInfo info, StreamingContext ctx) {
            fielda=(T) info.GetValue("fielda", typeof(T));
        }
        public void SetValue(T data) {
           fielda=data;
        }
        public T GetValue() {
           return fielda;
        }
        private T fielda=default(T);
    }
           
       








Related examples in the same category

1.A generic class with two generic parameters
2.Serialization for generic typeSerialization for generic type
3.Nested generic TypesNested generic Types
4. Output the type information about the generic parameters
5.Inherit Type Parameter
6.Call ToString on generic type
7.Nested Types
8.combining inheritance of generic types and constraints:
9.A generic Point structure.
10.Reference for Generic Types