对象之间通过反射拷贝数据
2009-08-29 11:35
363 查看
/// <summary> /// Copies the data of one object to another. The target object 'pulls' properties of the first. /// This any matching properties are written to the target. /// /// The object copy is a shallow copy only. Any nested types will be copied as /// whole values rather than individual property assignments (ie. via assignment) /// </summary> /// <param name="source">The source object to copy from</param> /// <param name="target">The object to copy to</param> /// <param name="excludedProperties">A comma delimited list of properties that should not be copied</param> /// <param name="memberAccess">Reflection binding access</param> public static void CopyObjectData(object source, object target, string excludedProperties, BindingFlags memberAccess) { string[] excluded = null; if (!string.IsNullOrEmpty(excludedProperties)) excluded = excludedProperties.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); MemberInfo[] miT = target.GetType().GetMembers(memberAccess); foreach (MemberInfo Field in miT) { string name = Field.Name; // Skip over any property exceptions if (!string.IsNullOrEmpty(excludedProperties) && excluded.Contains(name)) continue; if (Field.MemberType == MemberTypes.Field) { FieldInfo SourceField = source.GetType().GetField(name); if (SourceField == null) continue; object SourceValue = SourceField.GetValue(source); ((FieldInfo)Field).SetValue(target, SourceValue); } else if (Field.MemberType == MemberTypes.Property) { PropertyInfo piTarget = Field as PropertyInfo; PropertyInfo SourceField = source.GetType().GetProperty(name, memberAccess); if (SourceField == null) continue; if (piTarget.CanWrite && SourceField.CanRead) { object SourceValue = SourceField.GetValue(source, null); piTarget.SetValue(target, SourceValue, null); } } } }
下面两个参数跟据英文知道,
excludedProperties 这个参数可以是"属性1,属性2,属性3" 这样以逗号分隔的字符串 BindingFlags 就是枚举罗 BindingFlags bf = BindingFlags.Public | BindingFlags.Static......
string excludedProperties, BindingFlags memberAccess
相关文章推荐
- 通过反射完成不同对象之间的属性拷贝
- .NET中制做对象的副本(二)继承对象之间的数据拷贝
- 使用反射+缓存+委托,实现一个不同对象之间同名同类型属性值的快速拷贝
- .NET解析xml字符串,通过反射给实体类对象赋值,获取实体类数据列表
- 通过全局对象在Activity之间传递数据
- [C#] 不同类型的对象之间快速拷贝(比反射快十倍)
- 关于通过反射将表中的一行数据转换成某一具体的对象
- 通过反射将表中的一行数据转换成某一具体的对象
- java反射(5)通过反射拷贝对象
- (Siverlight应用程序之间)通过宿主(B屏)New对象,进行的交互消息(反射)
- 通过Java的反射机制实现对象的拷贝
- 使用反射+缓存+委托,实现一个不同对象之间同名同类型属性值的快速拷贝
- 通过反射,给对象之间赋值
- 重启图元遇到指定索引值重新绘制和glew通过NULL指定没有cpu数据拷贝到缓存区对象中
- java通过反射,泛型将定义的对象与对象之间互转
- 通过反射将表中的一行数据转换成某一具体的对象
- 通过URLConnection发送序列化对象的方式实验分布式系统之间的数据交互
- Java通过反射实现简单对象的拷贝
- 细粒度依赖(一)通过数据字典找到数据库对象之间的引用关系
- 使用反射+缓存+委托,实现一个不同对象之间同名同类型属性值的快速拷贝