Aynı tür için çalışan bir kod ararken, bu kod aynı özelliklere sahip diğer türleri de destekleyecektir.
Yansıma kullanır, ancak daha temiz bir şekilde. Convert.ChangeType
'a dikkat edin: buna ihtiyacınız olmayabilir; Dönüştürme yerine tür üzerinde bir kontrol yapabilirsiniz. Bu bir uzantısı yöntemidir yana
public static TConvert ConvertTo<TConvert>(this object entity) where TConvert : new()
{
var convertProperties = TypeDescriptor.GetProperties(typeof(TConvert)).Cast<PropertyDescriptor>();
var entityProperties = TypeDescriptor.GetProperties(entity).Cast<PropertyDescriptor>();
var convert = new TConvert();
foreach (var entityProperty in entityProperties)
{
var property = entityProperty;
var convertProperty = convertProperties.FirstOrDefault(prop => prop.Name == property.Name);
if (convertProperty != null)
{
convertProperty.SetValue(convert, Convert.ChangeType(entityProperty.GetValue(entity), convertProperty.PropertyType));
}
}
return convert;
}
, kullanım basit:
var result = original.ConvertTo<SomeOtherType>();
Bu aradığınız budur: ([C# Klonlama nesneler] https://stackoverflow.com/questions/ 78536/klonlama-c nesneleri-in-c) –