ProjectingDeserializer.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. using MongoDB.Bson.Serialization;
  21. using MongoDB.Bson.Serialization.Serializers;
  22. namespace MongoDB.Bson.Serialization.Serializers
  23. {
  24. /// <summary>
  25. /// Wraps a serializer and projects using a function.
  26. /// </summary>
  27. /// <typeparam name="TFrom">The type of from.</typeparam>
  28. /// <typeparam name="TTo">The type of to.</typeparam>
  29. public class ProjectingDeserializer<TFrom, TTo> : SerializerBase<TTo>
  30. {
  31. // private fields
  32. private readonly IBsonSerializer<TFrom> _fromSerializer;
  33. private readonly Func<TFrom, TTo> _projector;
  34. // constructors
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="ProjectingDeserializer{TFrom, TTo}"/> class.
  37. /// </summary>
  38. /// <param name="fromSerializer">From serializer.</param>
  39. /// <param name="projector">The projector.</param>
  40. public ProjectingDeserializer(IBsonSerializer<TFrom> fromSerializer, Func<TFrom, TTo> projector)
  41. {
  42. _fromSerializer = fromSerializer;
  43. _projector = projector;
  44. }
  45. /// <summary>
  46. /// Deserializes a value.
  47. /// </summary>
  48. /// <param name="context">The deserialization context.</param>
  49. /// <param name="args">The deserialization args.</param>
  50. /// <returns>A deserialized value.</returns>
  51. public override TTo Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
  52. {
  53. var from = _fromSerializer.Deserialize(context);
  54. return _projector(from);
  55. }
  56. }
  57. }