在 C#,快速复制一个对象的值给另一个对象(常常用于父类与子类之间相互复制)
2011-09-15 21:04 音乐让我说 阅读(2977) 评论(0) 编辑 收藏 举报直接贴代码了:
using System; using System.Collections.Generic; using System.ComponentModel; public static class ModelCopier { public static void CopyCollection<T>(IEnumerable<T> from, ICollection<T> to) { if (from == null || to == null || to.IsReadOnly) { return; } to.Clear(); foreach (T element in from) { to.Add(element); } } public static void CopyModel(object from, object to) { if (from == null || to == null) { return; } PropertyDescriptorCollection fromProperties = TypeDescriptor.GetProperties(from); PropertyDescriptorCollection toProperties = TypeDescriptor.GetProperties(to); foreach (PropertyDescriptor fromProperty in fromProperties) { PropertyDescriptor toProperty = toProperties.Find(fromProperty.Name, true /* ignoreCase */); if (toProperty != null && !toProperty.IsReadOnly) { // Can from.Property reference just be assigned directly to to.Property reference? bool isDirectlyAssignable = toProperty.PropertyType.IsAssignableFrom(fromProperty.PropertyType); // Is from.Property just the nullable form of to.Property? bool liftedValueType = (isDirectlyAssignable) ? false : (Nullable.GetUnderlyingType(fromProperty.PropertyType) == toProperty.PropertyType); if (isDirectlyAssignable || liftedValueType) { object fromValue = fromProperty.GetValue(from); if (isDirectlyAssignable || (fromValue != null && liftedValueType)) { toProperty.SetValue(to, fromValue); } } } } } }
谢谢浏览!
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。