Come fare se si volesse creare un Clone di un oggetto di tipo Foo1 ad un tipo Foo2 che ereditano da una stessa classe base? Ovvero, come fare un upcast? Avete i brividi eh? Beh come sempre sui news group si trovano le richieste più strane... :-).
public TRet Clone<TRet, TBase>(TBase obj) where TRet : TBase, new() {
TRet ret = new TRet();
PropertyInfo[] properties = typeof(TBase).GetProperties(
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public
);
foreach (PropertyInfo property in properties) {
object value = property.GetValue(obj, null);
property.SetValue(ret, value, null);
}
return ret;
}
Qui l'esempio di chiamata:
public class Foo1 : ICommonInterface {
public string Name { get; set; }
}
public class Foo2 : ICommonInterface {
public string Name { get; set; }
}
public interface ICommonInterface {
string Name { get; set; }
}
//Call sample
Foo1 foo1 = new Foo1 { Name = "Bill" };
Foo2 foo2 = Clone<Foo2, ICommonInterface>(foo1);
Matteo Migliore.