@@ -9,7 +9,7 @@ namespace Microsoft.OpenApi.Helpers
99 /// <summary>
1010 /// Helper class for deep cloning dictionaries.
1111 /// </summary>
12- internal class DictionaryCloneHelper
12+ internal static class DictionaryCloneHelper
1313 {
1414 /// <summary>
1515 /// Deep clone key value pairs in a dictionary.
@@ -21,14 +21,26 @@ internal class DictionaryCloneHelper
2121 internal static Dictionary < T , U > Clone < T , U > ( IDictionary < T , U > dictionary )
2222 {
2323 if ( dictionary is null ) return null ;
24+
2425 var clonedDictionary = new Dictionary < T , U > ( dictionary . Keys . Count ) ;
26+ var clonedObjects = new Dictionary < object , object > ( ) ;
2527
26- foreach ( var kvp in dictionary )
28+ foreach ( var keyValuePair in dictionary )
2729 {
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+ }
3244
3345 return clonedDictionary ;
3446 }
0 commit comments