复制&粘贴时间!
这是一个我在项目中使用的对象之间的合并数据:
public static void MergeFrom<T>(this object destination, T source)
{
Type destinationType = destination.GetType();
//in case we are dealing with DTOs or EF objects then exclude the EntityKey as we know it shouldn't be altered once it has been set
PropertyInfo[] propertyInfos = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => !string.Equals(x.Name, "EntityKey", StringComparison.InvariantCultureIgnoreCase)).ToArray();
foreach (var propertyInfo in propertyInfos)
{
PropertyInfo destinationPropertyInfo = destinationType.GetProperty(propertyInfo.Name, BindingFlags.Public | BindingFlags.Instance);
if (destinationPropertyInfo != null)
{
if (destinationPropertyInfo.CanWrite && propertyInfo.CanRead && (destinationPropertyInfo.PropertyType == propertyInfo.PropertyType))
{
object o = propertyInfo.GetValue(source, null);
destinationPropertyInfo.SetValue(destination, o, null);
}
}
}
}
如果您发现Where
条款我离开那里,它是从上榜排除特定的属性。我已经把它留在了这样你可以看到如何去做,你可能有一个你想排除的属性列表,无论出于何种原因。
你还会注意到,这样做是为扩展方法,这样我就可以这样使用它:
myTargetObject.MergeFrom(someSourceObject);
我不相信这是给这个任何真实姓名,除非你想使用“克隆”或“合并”。
好啊。这正是我需要的。谢谢一堆! – Nate222