Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Reflection;
- using System.IO;
- namespace NativeSerializer
- {
- static class NativeSerializer
- {
- public static void Serialize(Stream stream, object obj)
- {
- // get the fields
- Type type = obj.GetType();
- FieldInfo[] fiList = type.GetFields();
- // set up a writer
- var bw = new BinaryWriter(stream);
- // process each field
- foreach (FieldInfo fi in fiList)
- {
- // array?
- if (fi.FieldType.Name.EndsWith("[]"))
- {
- // get the array element type
- Type elementType = Type.GetType(fi.FieldType.FullName.TrimEnd('[', ']'));
- // pull out the value
- var array = (Array)fi.GetValue(obj);
- // write the length of the array
- bw.Write(array.Length);
- // write all of the data
- for (int i = 0; i < array.Length; i++)
- {
- typeof(BinaryWriter)
- .GetMethod("Write", new Type[] { elementType })
- .Invoke(bw, new object[] { array.GetValue(i) });
- }
- }
- else
- {
- // write the value
- typeof(BinaryWriter)
- .GetMethod("Write", new Type[] { fi.FieldType })
- .Invoke(bw, new object[] { fi.GetValue(obj) });
- }
- }
- }
- public static T Deserialize<T>(Stream stream)
- {
- // get fields of the class
- FieldInfo[] fiList = typeof(T).GetFields();
- // create an instance
- object obj = Activator.CreateInstance(typeof(T));
- var br = new BinaryReader(stream);
- // process each field
- foreach (FieldInfo fi in fiList)
- {
- // array?
- if (fi.FieldType.Name.EndsWith("[]"))
- {
- // get the element type
- Type elementType = Type.GetType(fi.FieldType.FullName.TrimEnd('[', ']'));
- // create the array instance based on the length specified
- var array = Array.CreateInstance(elementType, br.ReadInt32());
- // read out all the values and set the array
- for (int i = 0; i < array.Length; i++)
- {
- // set value for current index
- array.SetValue(
- typeof(BinaryReader)
- .GetMethod("Read" + elementType.Name)
- .Invoke(br, null),
- i
- );
- }
- // write the array back to the field
- fi.SetValue(obj, array);
- }
- else
- {
- // read and set the value
- fi.SetValue(obj,
- typeof(BinaryReader)
- .GetMethod("Read" + fi.FieldType.Name)
- .Invoke(br, null)
- );
- }
- }
- return (T)obj;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement