UnitySerializationHolder.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Runtime.Serialization;
  5. namespace System
  6. {
  7. /// <summary>
  8. /// Holds Null class for which we guarantee that there is only ever one instance of.
  9. /// This only exists for compatibility with .NET Framework.
  10. /// </summary>
  11. [Serializable]
  12. // Needs to be public to support binary serialization compatibility
  13. public sealed class UnitySerializationHolder : ISerializable, IObjectReference
  14. {
  15. internal const int NullUnity = 0x0002;
  16. private readonly int _unityType;
  17. private readonly string _data;
  18. /// <summary>
  19. /// A helper method that returns the SerializationInfo that a class utilizing
  20. /// UnitySerializationHelper should return from a call to GetObjectData. It contains
  21. /// the unityType (defined above) and any optional data (used only for the reflection types).
  22. /// </summary>
  23. internal static void GetUnitySerializationInfo(SerializationInfo info, int unityType)
  24. {
  25. info.SetType(typeof(UnitySerializationHolder));
  26. info.AddValue("Data", null, typeof(string));
  27. info.AddValue("UnityType", unityType);
  28. info.AddValue("AssemblyName", string.Empty);
  29. }
  30. public UnitySerializationHolder(SerializationInfo info, StreamingContext context)
  31. {
  32. if (info == null)
  33. {
  34. throw new ArgumentNullException(nameof(info));
  35. }
  36. // We are ignoring any other serialization input as we are only concerned about DBNull.
  37. // We also store data and use it for erorr logging.
  38. _unityType = info.GetInt32("UnityType");
  39. _data = info.GetString("Data");
  40. }
  41. public void GetObjectData(SerializationInfo info, StreamingContext context) =>
  42. throw new NotSupportedException(SR.NotSupported_UnitySerHolder);
  43. public object GetRealObject(StreamingContext context)
  44. {
  45. // We are only support deserializing DBNull and throwing for everything else.
  46. if (_unityType != NullUnity)
  47. {
  48. throw new ArgumentException(SR.Format(SR.Argument_InvalidUnity, _data ?? "UnityType"));
  49. }
  50. // We are always returning the same DBNull instance.
  51. return DBNull.Value;
  52. }
  53. }
  54. }