@@ -9,7 +9,7 @@ namespace Microsoft.OpenApi.Helpers
9
9
/// <summary>
10
10
/// Helper class for deep cloning dictionaries.
11
11
/// </summary>
12
- internal class DictionaryCloneHelper
12
+ internal static class DictionaryCloneHelper
13
13
{
14
14
/// <summary>
15
15
/// Deep clone key value pairs in a dictionary.
@@ -21,14 +21,26 @@ internal class DictionaryCloneHelper
21
21
internal static Dictionary < T , U > Clone < T , U > ( IDictionary < T , U > dictionary )
22
22
{
23
23
if ( dictionary is null ) return null ;
24
+
24
25
var clonedDictionary = new Dictionary < T , U > ( dictionary . Keys . Count ) ;
26
+ var clonedObjects = new Dictionary < object , object > ( ) ;
25
27
26
- foreach ( var kvp in dictionary )
28
+ foreach ( var keyValuePair in dictionary )
27
29
{
28
- // Create instance of the specified type using the constructor matching the specified parameter types.
29
- clonedDictionary [ kvp . Key ] = ( U ) Activator . CreateInstance ( kvp . Value . GetType ( ) , kvp . Value ) ;
30
- }
31
-
30
+ // If the object has already been cloned, use the cloned object instead of cloning it again
31
+ if ( clonedObjects . TryGetValue ( keyValuePair . Value , out var clonedValue ) )
32
+ {
33
+ clonedDictionary [ keyValuePair . Key ] = ( U ) clonedValue ;
34
+ }
35
+ else
36
+ {
37
+ // Create instance of the specified type using the constructor matching the specified parameter types.
38
+ clonedDictionary [ keyValuePair . Key ] = ( U ) Activator . CreateInstance ( keyValuePair . Value . GetType ( ) , keyValuePair . Value ) ;
39
+
40
+ // Add the cloned object to the dictionary of cloned objects
41
+ clonedObjects . Add ( keyValuePair . Value , clonedDictionary [ keyValuePair . Key ] ) ;
42
+ }
43
+ }
32
44
33
45
return clonedDictionary ;
34
46
}
0 commit comments