ObjectIDGenerator.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // System.Runtime.Serialization.ObjectIDGenerator.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. using System.Runtime.Serialization;
  12. namespace System.Runtime.Serialization
  13. {
  14. [Serializable]
  15. public class ObjectIDGenerator
  16. {
  17. // Private field
  18. Hashtable table;
  19. long current; // this is the current ID, starts at 1
  20. // ObjectIDGenerator must generate a new id for each object instance.
  21. // If two objects have the same state (i.e. the method Equals() returns true),
  22. // each one should have a different id.
  23. // Thus, the object instance cannot be directly used as key of the hashtable.
  24. // The key is then a wrapper of the object that compares object references
  25. // instead of object content (unless the object is inmutable, like strings).
  26. struct InstanceWrapper
  27. {
  28. object _instance;
  29. public InstanceWrapper (object instance)
  30. {
  31. _instance = instance;
  32. }
  33. public override bool Equals (object other)
  34. {
  35. InstanceWrapper ow = (InstanceWrapper)other;
  36. if (_instance.GetType() == typeof(string))
  37. return _instance.Equals(ow._instance);
  38. else
  39. return (_instance == ow._instance);
  40. }
  41. public override int GetHashCode ()
  42. {
  43. return _instance.GetHashCode();
  44. }
  45. }
  46. // constructor
  47. public ObjectIDGenerator ()
  48. : base ()
  49. {
  50. table = new Hashtable ();
  51. current = 1;
  52. }
  53. // Methods
  54. public virtual long GetId (object obj, out bool firstTime)
  55. {
  56. if (obj == null)
  57. throw new ArgumentNullException ("The obj parameter is null.");
  58. InstanceWrapper iw = new InstanceWrapper(obj);
  59. if (table.ContainsKey (iw)) {
  60. firstTime = false;
  61. return (long) table [iw];
  62. } else {
  63. firstTime = true;
  64. table.Add (iw, current);
  65. return current ++;
  66. }
  67. }
  68. public virtual long HasId (object obj, out bool firstTime)
  69. {
  70. if (obj == null)
  71. throw new ArgumentNullException ("The obj parameter is null.");
  72. InstanceWrapper iw = new InstanceWrapper(obj);
  73. if (table.ContainsKey (iw))
  74. {
  75. firstTime = false;
  76. return (long) table [iw];
  77. } else {
  78. firstTime = true;
  79. return 0L; // 0 is the null ID
  80. }
  81. }
  82. }
  83. }