複製&粘貼時間!
這是一個我在項目中使用的對象之間的合併數據:
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