internal static void Write(object e, int tag, TarsOutputStream jos) { TarsStructInfo info = TarsHelper.GetStructInfo(e.GetType()); if (info == null) { throw new TarsDecodeException("the class type[" + e.GetType().FullName + "] no attribute Struct"); } jos.WriteHead(TarsStructBase.STRUCT_BEGIN, tag); List <TarsStructPropertyInfo> propertysList = info.PropertyList; foreach (var propertyInfo in propertysList) { Object value = propertyInfo.PropertyAccessor.GetValue(e); if (value == null && propertyInfo.IsRequire) { throw new TarsEncodeException(propertyInfo.Name + " is require tag ,order=" + propertyInfo.Order); } if (value != null) { jos.Write(value, propertyInfo.Order); } } jos.WriteHead(TarsStructBase.STRUCT_END, 0); }
internal static object Read(Type type, int tag, bool isRequire, TarsInputStream jis) { TarsStructInfo info = TarsHelper.GetStructInfo(type); if (info == null) { throw new TarsDecodeException("the class type[" + type.FullName + "] no attribute Struct"); } if (jis.SkipToTag(tag)) { HeadData hd = new HeadData(); jis.ReadHead(hd); if (hd.Type != TarsStructBase.STRUCT_BEGIN) { throw new TarsDecodeException("type mismatch."); } Object result = info.ConstructorInvoker.Invoke(); List <TarsStructPropertyInfo> propertysList = info.PropertyList; foreach (var propertyInfo in propertysList) { Object value = jis.Read(propertyInfo.Type, propertyInfo.Order, propertyInfo.IsRequire); propertyInfo.PropertyAccessor.SetValue(result, value); } jis.SkipToStructEnd(); return(result); } else if (isRequire) { throw new TarsDecodeException("require field not exist."); } return(null); }
//获取结构体详情 internal static TarsStructInfo GetStructInfo(Type type) { TarsStructInfo structInfo = tarsStructCache.GetOrAdd(type, t => { TarsStructInfo tarsStructInfo = new TarsStructInfo(); PropertyInfo[] fields = type.GetProperties(System.Reflection.BindingFlags.Public); if (fields.Length > 0) { List <TarsStructPropertyInfo> propertyList = new List <TarsStructPropertyInfo>(); foreach (var item in fields) { TarsStructPropertyAttribute attri = item.GetCustomAttribute <TarsStructPropertyAttribute>(); if (attri != null) { TarsStructPropertyInfo propertyInfo = new TarsStructPropertyInfo(); Type fieldType = item.PropertyType; propertyInfo.Name = item.Name; propertyInfo.Order = attri.Order; propertyInfo.IsRequire = attri.IsRequire; propertyInfo.Comment = attri.Comment; propertyInfo.PropertyAccessor = new PropertyAccessor(item); propertyInfo.Type = fieldType; propertyList.Add(propertyInfo); } } TarsStructAttribute structAttribute = type.GetCustomAttribute <TarsStructAttribute>(); propertyList.Sort((x, y) => x.Order.CompareTo(y.Order)); tarsStructInfo.PropertyList = propertyList; tarsStructInfo.ConstructorInvoker = new ConstructorInvoker(type.GetConstructor(EmptyTypeArray)); if (structAttribute != null) { string comment = structAttribute.Comment; if (string.IsNullOrWhiteSpace(comment)) { tarsStructInfo.Comment = comment; } } } return(tarsStructInfo); }); return(structInfo); }