Nothing is known about the types at compile time.
object TransformObject(object oldObject, Type newType, Func<object, object> transform)
{
if(obj.GetType().ImplementsGenericInterface(typeof(IList<>))
&& newType.ImplementsGenericInterface(typeof(IList<>)))
{
object newCollection = Activator.CreateInstance(newType);
// This is where it gets tricky:
// 1. How to iterate over the old collection?
// 2. How to add each element in the new collection?
object oldCollection = oldObject;
foreach(var oldItem in oldCollection)
{
object newItem = transform(oldItem);
newCollection.Add(newItem);
}
// 3. How to ensure that the order in the new collection is preserved?
return newCollection;
}
return null;
}
Naturally this doesn't work.
What is known at run-time:
oldCollection.GetType()
implements typeIList<AT>
.newType
implements typeIList<BT>
- Function
object transform(object oldObject)
takes care of converting object of typeAT
into a new object of typeBT
. Or maps object into an object of different type. Mapping is not known compile-time.
Aucun commentaire:
Enregistrer un commentaire