/// <summary> /// Deserializes the object from this stream /// </summary> /// <param name="reader">Input stream</param> /// <param name="readInternal">Optional delegate to create the object</param> public static T ReadRWObject <T>(this BinaryReader reader, BinaryRWObjectExtensions.ReadObjectFully readInternal = null) { if (readInternal == null) { // Try to find a constructor... System.Reflection.ConstructorInfo ctr = typeof(T).GetConstructor(new Type[0]); if (ctr == null) { throw new IOException("Can't read " + typeof(T).Name + " directly!\n"); } else { readInternal = (BinaryReader rdr) => { BinaryRWObject ro = (BinaryRWObject)ctr.Invoke(new object[0]); ro.ReadBinaryData(rdr); return(ro); }; } } return((T)readInternal(reader)); }
public static T[] ReadArray <T>(this BinaryReader reader, BinaryRWObjectExtensions.ReadObjectFully readInternal = null) { if (typeof(BinaryRWObject).IsAssignableFrom(typeof(T))) { if (readInternal == null) { // Try to find a constructor... ConstructorInfo ctr = typeof(T).GetConstructor(new Type[0]); if (ctr == null) { throw new IOException("Can't read array of RWObjects directly!\n"); } readInternal = (BinaryReader rdr) => { BinaryRWObject ro = (BinaryRWObject)ctr.Invoke(new object[0]); ro.ReadBinaryData(rdr); return(ro); }; } T[] arr = new T[reader.ReadInt32()]; for (int i = 0; i < arr.Length; i++) { arr[i] = (T)readInternal(reader); } return(arr); } else if (typeof(T).IsPrimitive) { int len = reader.ReadInt32(); int size = Buffer.ByteLength(new T[1]); byte[] res = new byte[len * size]; int count = reader.Read(res, 0, res.Length); while (count != res.Length) { int read = reader.Read(res, count, res.Length - count); count += read; if (read < 0) { throw new IOException("Failed to read enough bytes to fill array!\n"); } } T[] dest = new T[len]; Buffer.BlockCopy(res, 0, dest, 0, res.Length); return(dest); } else { MethodInfo tMeth = typeof(BinaryReader).GetMethod("Read" + typeof(T).Name); if (tMeth == null) { throw new IOException("Unsupported read object."); } T[] arr = new T[reader.ReadInt32()]; for (int i = 0; i < arr.Length; i++) { arr[i] = (T)tMeth.Invoke(reader, new object[0]); } return(arr); } }