/// <summary> /// 序列化 /// </summary> /// <returns>The encode.</returns> /// <param name="val">要序列化的对象</param> public static GenericCollectionValue Serialize(object val) { GenericCollectionValue genericVal = null; if (val is null) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Null }; } else if (val is byte[]) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Bytes, BytesValue = ByteString.CopyFrom((byte[])val) }; } else if (val is byte) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Byte, IntValue = (byte)val }; } else if (val is short) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Short, IntValue = (short)val }; } else if (val is int) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Int, IntValue = (int)val }; } else if (val is long) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Long, LongIntValue = (long)val }; } else if (val is bool) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Bool, BoolValue = (bool)val }; } else if (val is float) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Float, FloatValue = (float)val }; } else if (val is double) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Double, DoubleValue = (double)val }; } else if (val is string) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.String, StringValue = (string)val }; } else if (val is PlayObject playObject) { var bytes = SerializePlayObject(playObject); genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Map, BytesValue = ByteString.CopyFrom(bytes) }; } else if (val is PlayArray playArray) { var collection = new GenericCollection(); foreach (object obj in playArray) { collection.ListValue.Add(Serialize(obj)); } genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Array, BytesValue = collection.ToByteString() }; } else { var type = val.GetType(); if (typeDict.TryGetValue(type, out var customType)) { genericVal = new GenericCollectionValue { Type = GenericCollectionValue.Types.Type.Object, ObjectTypeId = customType.TypeId, BytesValue = ByteString.CopyFrom(customType.SerializeMethod(val)) }; } else { throw new Exception($"{type} is not supported"); } } return(genericVal); }