SerializationContext.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. namespace ProtoBuf
  3. {
  4. /// <summary>
  5. /// Additional information about a serialization operation
  6. /// </summary>
  7. public sealed class SerializationContext
  8. {
  9. private bool frozen;
  10. internal void Freeze() { frozen = true;}
  11. private void ThrowIfFrozen() { if (frozen) throw new InvalidOperationException("The serialization-context cannot be changed once it is in use"); }
  12. private object context;
  13. /// <summary>
  14. /// Gets or sets a user-defined object containing additional information about this serialization/deserialization operation.
  15. /// </summary>
  16. public object Context
  17. {
  18. get { return context; }
  19. set { if (context != value) { ThrowIfFrozen(); context = value; } }
  20. }
  21. private static readonly SerializationContext @default;
  22. static SerializationContext()
  23. {
  24. @default = new SerializationContext();
  25. @default.Freeze();
  26. }
  27. /// <summary>
  28. /// A default SerializationContext, with minimal information.
  29. /// </summary>
  30. internal static SerializationContext Default { get {return @default;}}
  31. #if PLAT_BINARYFORMATTER || (SILVERLIGHT && NET_4_0)
  32. #if !(WINRT || PHONE7 || PHONE8 || COREFX)
  33. private System.Runtime.Serialization.StreamingContextStates state = System.Runtime.Serialization.StreamingContextStates.Persistence;
  34. /// <summary>
  35. /// Gets or sets the source or destination of the transmitted data.
  36. /// </summary>
  37. public System.Runtime.Serialization.StreamingContextStates State
  38. {
  39. get { return state; }
  40. set { if (state != value) { ThrowIfFrozen(); state = value; } }
  41. }
  42. #endif
  43. /// <summary>
  44. /// Convert a SerializationContext to a StreamingContext
  45. /// </summary>
  46. public static implicit operator System.Runtime.Serialization.StreamingContext(SerializationContext ctx)
  47. {
  48. #if WINRT || PHONE7 || PHONE8 || COREFX
  49. return new System.Runtime.Serialization.StreamingContext();
  50. #else
  51. if (ctx == null) return new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence);
  52. return new System.Runtime.Serialization.StreamingContext(ctx.state, ctx.context);
  53. #endif
  54. }
  55. /// <summary>
  56. /// Convert a StreamingContext to a SerializationContext
  57. /// </summary>
  58. public static implicit operator SerializationContext (System.Runtime.Serialization.StreamingContext ctx)
  59. {
  60. SerializationContext result = new SerializationContext();
  61. #if !(WINRT || PHONE7 || PHONE8 || COREFX)
  62. result.Context = ctx.Context;
  63. result.State = ctx.State;
  64. #endif
  65. return result;
  66. }
  67. #endif
  68. }
  69. }