public static DictionaryData <T> Parse <T>(object data, Action <T, object> onParseItem = null) where T : IData, new() { DictionaryData <T> obj = new DictionaryData <T>(); obj.Parse(data, onParseItem); return(obj); }
public void Parse(object data) { Type objtype = this.GetType(); Type datatype = data.GetType(); List <ParseStruct> all = new List <ParseStruct>(); FieldInfo[] datafields = datatype.GetFields(); for (int i = 0; i < datafields.Length; i++) { FieldInfo datafi = datafields[i]; object datav = datafi.GetValue(data); if (datav == null) { continue; } all.Add(new ParseStruct() { Name = datafi.Name, Type = datafi.FieldType, Value = datav }); } PropertyInfo[] dataproperties = datatype.GetProperties(); for (int i = 0; i < dataproperties.Length; i++) { PropertyInfo property = dataproperties[i]; object datav = property.GetValue(data); if (datav == null) { continue; } all.Add(new ParseStruct() { Name = property.Name, Type = property.PropertyType, Value = datav }); } for (int i = 0; i < all.Count; i++) { ParseStruct parseStruct = all[i]; FieldInfo objfi = objtype.GetField(parseStruct.Name); if (objfi == null || !typeof(IData).IsAssignableFrom(objfi.FieldType)) { continue; } bool isList = objfi.FieldType.IsGenericType && objfi.FieldType.GetGenericTypeDefinition() == typeof(ListData <>); bool isDict = objfi.FieldType.IsGenericType && objfi.FieldType.GetGenericTypeDefinition() == typeof(DictionaryData <>); bool isStruct = typeof(StructData).IsAssignableFrom(objfi.FieldType); bool isBase = objfi.FieldType.BaseType.IsGenericType && objfi.FieldType.BaseType.GetGenericTypeDefinition() == typeof(BaseData <>) && objfi.FieldType.BaseType.GetGenericArguments()[0] == parseStruct.Type; object objv = objfi.GetValue(this); if (objv != null) { if (isList) { (objv as IListData).ParseObject(parseStruct.Value); } else if (isDict) { (objv as IDictionaryData).ParseObject(parseStruct.Value); } else if (isStruct) { (objv as StructData).Parse(parseStruct.Value); } else if (isBase) { (objv as IBaseData).FastSetValue(parseStruct.Value); } } else { if (isList) { objfi.SetValue(this, ListData.Parse(objfi.FieldType.GetGenericArguments()[0], parseStruct.Value)); } else if (isDict) { objfi.SetValue(this, DictionaryData.Parse(objfi.FieldType.GetGenericArguments()[0], parseStruct.Value)); } else if (isStruct) { objfi.SetValue(this, StructData.Parse(objfi.FieldType, parseStruct.Value)); } else if (isBase) { objfi.SetValue(this, Activator.CreateInstance(objfi.FieldType, parseStruct.Value)); } } } }