Boolean TryRead(Object target, DME_BinaryReader reader, DME_MemberInfo member, Boolean encodeInt, Boolean allowNull, out Object value) { Type type = member.Type; // 基本类型 if (reader.TryReadValue(type, encodeInt, out value)) return true; // 允许空时,先读取一个字节判断对象是否为空 if (allowNull && reader.ReadByte() == 0) return true; #region 接口支持 //if (Array.IndexOf(member.Type.GetInterfaces(), typeof(IBinaryAccessor)) >= 0) if (typeof(DME_IBinaryAccessor).IsAssignableFrom(member.Type)) { // 读取对象 Object obj = member.GetValue(target); // 实例化对象 if (obj == null) { obj = Activator.CreateInstance(type); member.SetValue(target, obj); } if (obj == null) return false; // 调用接口 DME_IBinaryAccessor accessor = obj as DME_IBinaryAccessor; accessor.Read(reader); return true; } #endregion #region 枚举 if (typeof(IEnumerable).IsAssignableFrom(member.Type)) { // 先读元素个数 Int32 count = reader.ReadEncodedInt32(); if (count < 0) throw new InvalidOperationException("无效元素个数" + count + "!"); Type elementType = member.Type; if (member.Type.HasElementType) elementType = member.Type.GetElementType(); else if (member.Type.IsGenericType) { Type[] ts = member.Type.GetGenericArguments(); if (ts != null && ts.Length > 0) elementType = ts[0]; } Array arr = Array.CreateInstance(elementType, count); for (int i = 0; i < count; i++) { if (allowNull && reader.ReadEncodedInt32() == 0) continue; Object obj = null; if (!reader.TryReadValue(elementType, encodeInt, out obj)) { obj = CreateInstance(elementType); Read(obj, reader, encodeInt, allowNull, member.Member.MemberType == MemberTypes.Property); } arr.SetValue(obj, i); } value = Activator.CreateInstance(member.Type, arr); return true; } #endregion return false; }
/// <summary> /// 从读取器中读取数据到对象的成员中 /// </summary> /// <param name="target">目标</param> /// <param name="reader">读取器</param> /// <param name="member">成员</param> /// <param name="encodeInt">使用7Bit编码整数</param> /// <param name="allowNull">是否允许对象为空,如果允许,则读取时先读取一个字节判断对象是否为空</param> protected virtual void ReadMember(Object target, DME_BinaryReader reader, DME_MemberInfo member, Boolean encodeInt, Boolean allowNull) { Object value = null; MemberTypes mt = member.Member.MemberType; if (mt == MemberTypes.Field || mt == MemberTypes.Property) { if (!TryRead(target, reader, member, encodeInt, allowNull, out value)) throw new InvalidOperationException("无法读取数据,如果是复杂类型请实现IBinaryAccessor接口。"); member.SetValue(target, value); } else throw new ArgumentOutOfRangeException("member", "成员只能是FieldInfo或PropertyInfo。"); }