Copy the property values to another object with C#
This question already has an answer here:
public static void CopyPropertiesTo<T, TU>(this T source, TU dest)
{
var sourceProps = typeof (T).GetProperties().Where(x => x.CanRead).ToList();
var destProps = typeof(TU).GetProperties()
.Where(x => x.CanWrite)
.ToList();
foreach (var sourceProp in sourceProps)
{
if (destProps.Any(x => x.Name == sourceProp.Name))
{
var p = destProps.First(x => x.Name == sourceProp.Name);
if(p.CanWrite) { // check if the property can be set or no.
p.SetValue(dest, sourceProp.GetValue(source, null), null);
}
}
}
}
This is a function that I used to copy members between models in ASP.NET MVC. While you seek a code that work for the same type, this code will also support other types that has the same properties.
It uses reflections, but in a more clean manner. Beware of the Convert.ChangeType
: you might not need it; you could do a check on the type instead of converting.
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;
}
Since this is an extension method, the usage is simple:
var result = original.ConvertTo<SomeOtherType>();
If I am not mistaken with what is required, the way to easily achieve property value copy between two existing instances (even not of the same type) is to use Automapper.
As long as you keep property in same type and in same naming convention, all should work.
Example:
MapperConfiguration _configuration = new MapperConfiguration(cnf =>
{
cnf.CreateMap<SourceType, TargetType>();
});
var mapper = new Mapper(_configuration);
maper.DefaultContext.Mapper.Map(source, target)
链接地址: http://www.djcxy.com/p/40758.html
上一篇: 如何制作参考类型的副本
下一篇: 使用C#将属性值复制到另一个对象