Author Topic: fix the TNSerializer problem  (Read 1769 times)

onlyfeng

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 2
    • View Profile
fix the TNSerializer problem
« on: January 22, 2015, 09:37:17 PM »
When I use the TNSerializer to auto serializer custom object, It will have problem with some complex struct.
I debug it and find the problem is the static function: FilterFields, it use the static param: mFieldNames, mFieldValues, this will be overwrite in recursion logic.

I change the FilterFields use new variable, and it work fine now, maybe can help someone.

  1. static void FilterFields(object obj, out List<string> fieldNames, out List<object> fieldValues)
  2. {
  3.   Type type = obj.GetType();
  4.   List<FieldInfo> fields = type.GetSerializableFields();
  5.  
  6.   fieldNames = new List<string>();
  7.   fieldValues = new List<object>();
  8.  
  9.   for (int i = 0; i < fields.size; ++i)
  10.   {
  11.     FieldInfo f = fields[i];
  12.     object val = f.GetValue(obj);
  13.  
  14.     if (val != null)
  15.     {
  16.       fieldNames.Add(f.Name);
  17.       fieldValues.Add(val);
  18.     }
  19.   }
  20. }
  21.  
  22. case 254: // Serialization using Reflection
  23. {
  24. #if REFLECTION_SUPPORT
  25.   List<string> fieldNames;
  26.   List<object> fieldValues;
  27.   FilterFields(obj, out fieldNames, out fieldValues);
  28.   bw.WriteInt(fieldNames.size);
  29.  
  30.   for (int i = 0, imax = fieldNames.size; i < imax; ++i)
  31.   {
  32.     bw.Write(fieldNames[i]);
  33.     bw.WriteObject(fieldValues[i]);
  34.   }
  35. #else
  36.   Debug.LogError("Reflection-based serialization is not supported on this platform.");
  37. #endif
  38.   break;
  39. }
  40.  

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: fix the TNSerializer problem
« Reply #1 on: January 23, 2015, 10:02:48 PM »
They're static to avoid memory allocations.

If you have a complex class like that, consider simply adding a custom serializer for it by implementing the IBinarySerializable interface. As an added benefit, you'll cut on bandwidth.