SurrogateSelector.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // System.Runtime.Serialization.SurrogateSelector.cs
  3. //
  4. // Author: Duncan Mak ([email protected])
  5. //
  6. // (C) Ximian, Inc.
  7. //
  8. using System;
  9. using System.Collections;
  10. namespace System.Runtime.Serialization
  11. {
  12. public class SurrogateSelector : ISurrogateSelector
  13. {
  14. // Fields
  15. Hashtable Surrogates = new Hashtable ();
  16. string currentKey = null; // current key of Surrogates
  17. internal struct Bundle
  18. {
  19. public ISerializationSurrogate surrogate;
  20. public ArrayList selectors;
  21. public Bundle (ISerializationSurrogate surrogate)
  22. {
  23. this.surrogate = surrogate;
  24. selectors = new ArrayList ();
  25. }
  26. }
  27. // Constructor
  28. public SurrogateSelector()
  29. : base ()
  30. {
  31. }
  32. // Methods
  33. public virtual void AddSurrogate (Type type,
  34. StreamingContext context, ISerializationSurrogate surrogate)
  35. {
  36. if (type == null || surrogate == null)
  37. throw new ArgumentNullException ("Null reference.");
  38. currentKey = type.FullName + "#" + context.ToString ();
  39. if (Surrogates.ContainsKey (currentKey))
  40. throw new ArgumentException ("A surrogate for " + type.FullName + " already exists.");
  41. Bundle values = new Bundle (surrogate);
  42. Surrogates.Add (currentKey, values);
  43. }
  44. public virtual void ChainSelector (ISurrogateSelector selector)
  45. {
  46. if (selector == null)
  47. throw new ArgumentNullException ("Selector is null.");
  48. Bundle current = (Bundle) Surrogates [currentKey];
  49. current.selectors.Add (selector);
  50. }
  51. public virtual ISurrogateSelector GetNextSelector ()
  52. {
  53. Bundle current = (Bundle) Surrogates [currentKey];
  54. return (ISurrogateSelector) current.selectors [current.selectors.Count];
  55. }
  56. public virtual ISerializationSurrogate GetSurrogate (Type type,
  57. StreamingContext context, out ISurrogateSelector selector)
  58. {
  59. if (type == null)
  60. throw new ArgumentNullException ("type is null.");
  61. string key = type.FullName + "#" + context.ToString ();
  62. Bundle current = (Bundle) Surrogates [key];
  63. selector = (ISurrogateSelector) current.selectors [current.selectors.Count - 1];
  64. return (ISerializationSurrogate) current.surrogate;
  65. }
  66. public virtual void RemoveSurrogate (Type type, StreamingContext context)
  67. {
  68. if (type == null)
  69. throw new ArgumentNullException ("type is null.");
  70. string key = type.FullName + "#" + context.ToString ();
  71. Surrogates.Remove (key);
  72. }
  73. }
  74. }