SurrogateSelector.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // System.Runtime.Serialization.SurrogateSelector.cs
  3. //
  4. // Author: Duncan Mak ([email protected])
  5. // Lluis Sanchez ([email protected])
  6. //
  7. // (C) Ximian, Inc.
  8. //
  9. using System;
  10. using System.Collections;
  11. namespace System.Runtime.Serialization
  12. {
  13. public class SurrogateSelector : ISurrogateSelector
  14. {
  15. // Fields
  16. Hashtable Surrogates = new Hashtable ();
  17. ISurrogateSelector nextSelector = null;
  18. // Constructor
  19. public SurrogateSelector()
  20. : base ()
  21. {
  22. }
  23. // Methods
  24. public virtual void AddSurrogate (Type type,
  25. StreamingContext context, ISerializationSurrogate surrogate)
  26. {
  27. if (type == null || surrogate == null)
  28. throw new ArgumentNullException ("Null reference.");
  29. string currentKey = type.FullName + "#" + context.ToString ();
  30. if (Surrogates.ContainsKey (currentKey))
  31. throw new ArgumentException ("A surrogate for " + type.FullName + " already exists.");
  32. Surrogates.Add (currentKey, surrogate);
  33. }
  34. public virtual void ChainSelector (ISurrogateSelector selector)
  35. {
  36. if (selector == null)
  37. throw new ArgumentNullException ("Selector is null.");
  38. // Chain the selector at the beggining of the chain
  39. // since "The last selector added to the list will be the first one checked"
  40. // (from MS docs)
  41. if (nextSelector != null)
  42. selector.ChainSelector (nextSelector);
  43. nextSelector = selector;
  44. }
  45. public virtual ISurrogateSelector GetNextSelector ()
  46. {
  47. return nextSelector;
  48. }
  49. public virtual ISerializationSurrogate GetSurrogate (Type type,
  50. StreamingContext context, out ISurrogateSelector selector)
  51. {
  52. if (type == null)
  53. throw new ArgumentNullException ("type is null.");
  54. // Check this selector, and if the surrogate is not found,
  55. // check the chained selectors
  56. string key = type.FullName + "#" + context.ToString ();
  57. ISerializationSurrogate surrogate = (ISerializationSurrogate) Surrogates [key];
  58. if (surrogate != null) {
  59. selector = this;
  60. return surrogate;
  61. }
  62. if (nextSelector != null)
  63. return nextSelector.GetSurrogate (type, context, out selector);
  64. else {
  65. selector = null;
  66. return null;
  67. }
  68. }
  69. public virtual void RemoveSurrogate (Type type, StreamingContext context)
  70. {
  71. if (type == null)
  72. throw new ArgumentNullException ("type is null.");
  73. string key = type.FullName + "#" + context.ToString ();
  74. Surrogates.Remove (key);
  75. }
  76. }
  77. }