|
14 | 14 | */
|
15 | 15 |
|
16 | 16 | using System;
|
| 17 | +using System.Collections; |
17 | 18 | using System.Collections.Generic;
|
| 19 | +using System.Collections.ObjectModel; |
18 | 20 | using System.IO;
|
19 | 21 | using System.Linq;
|
20 | 22 | using System.Text;
|
@@ -43,6 +45,19 @@ public class T
|
43 | 45 | public SortedList<object, object> SL { get; set; }
|
44 | 46 | }
|
45 | 47 |
|
| 48 | + public class RO<TKey, TValue> : ReadOnlyDictionary<TKey, TValue> |
| 49 | + { |
| 50 | + private RO(IDictionary<TKey, TValue> dictionary) |
| 51 | + : base(dictionary) |
| 52 | + { |
| 53 | + } |
| 54 | + |
| 55 | + public static RO<TKey, TValue> ConstructorReplacement(IDictionary<TKey, TValue> dictionary) |
| 56 | + { |
| 57 | + return new RO<TKey, TValue>(dictionary); |
| 58 | + } |
| 59 | + } |
| 60 | + |
46 | 61 | [Test]
|
47 | 62 | public void TestNull()
|
48 | 63 | {
|
@@ -388,6 +403,28 @@ public void TestMixedPrimitiveTypesWithMixedKeys()
|
388 | 403 | Assert.Throws<BsonSerializationException>(() => obj.ToBson());
|
389 | 404 | }
|
390 | 405 |
|
| 406 | + [Test] |
| 407 | + public void TestImmutablePrivateConstructorDictionaryImplementation() |
| 408 | + { |
| 409 | + var d = new Dictionary<object, object> { { "A", new C { P = "x" } } }; |
| 410 | + var id = RO<object, object>.ConstructorReplacement(d); |
| 411 | + var sd = CreateSortedDictionary(d); |
| 412 | + var sl = CreateSortedList(d); |
| 413 | + var obj = new T { D = d, ID = id, SD = sd, SL = sl }; |
| 414 | + var json = obj.ToJson(); |
| 415 | + var rep = "{ 'A' : { '_t' : 'DictionaryGenericSerializers.C', 'P' : 'x' } }"; |
| 416 | + var expected = "{ 'D' : #R, 'ID' : #R, 'SD' : #R, 'SL' : #R }".Replace("#R", rep).Replace("'", "\""); |
| 417 | + Assert.AreEqual(expected, json); |
| 418 | + |
| 419 | + var bson = obj.ToBson(); |
| 420 | + var rehydrated = BsonSerializer.Deserialize<T>(bson); |
| 421 | + Assert.IsInstanceOf<Dictionary<object, object>>(rehydrated.D); |
| 422 | + Assert.IsInstanceOf<Dictionary<object, object>>(rehydrated.ID); |
| 423 | + Assert.IsInstanceOf<SortedDictionary<object, object>>(rehydrated.SD); |
| 424 | + Assert.IsInstanceOf<SortedList<object, object>>(rehydrated.SL); |
| 425 | + Assert.IsTrue(bson.SequenceEqual(rehydrated.ToBson())); |
| 426 | + } |
| 427 | + |
391 | 428 | private SortedDictionary<object, object> CreateSortedDictionary(Dictionary<object, object> d)
|
392 | 429 | {
|
393 | 430 | var sd = new SortedDictionary<object, object>();
|
|
0 commit comments