mardi 21 juillet 2020

Deep Clone ICollection

Consider there is method which performs deep clone of any type

T Clone<T>(T obj) { /**/ }

and also consider that method which performs a copy of singular object smth like this

object CopyObject(object obj)

already implemented

So I need return

ICollection<T>

after iterating and copying each object seperately

Expected Result

            var collection = new Collection<int>();
            collection.Add(1);
            collection.Add(2);
            ICollection<int> things = collection;
            var cloned = Clone(things);
            //Assert cloned is ICollection<int> , not List, not IList, not anything else

Solution like this

     var collectionGenericType = typeof(Collection<>).MakeGenericType(underlyingType);
                        var genericCollectionInstance = Activator.CreateInstance(collectionGenericType, buffer);
                      
return (T)Convert.ChangeType(genericCollectionInstance, typeof(T));
        

not worked it throws "System.InvalidCastException: Object must implement IConvertible"

This solution what I currently use

 var collectionGenericType = typeof(List<>).MakeGenericType(underlyingType);
                            var genericCollectionInstance = Activator.CreateInstance(collectionGenericType, buffer);
                          
    return (T)Convert.ChangeType(genericCollectionInstance, typeof(T));

is working, but it is creating List.

buffer is an array where all items of source are already deep cloned

underlyingType is Type which lays under generic class (e.g. ICollection it will be System.Int32)





Aucun commentaire:

Enregistrer un commentaire