在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
直接贴代码了: 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); } } } } } }
谢谢浏览! |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论