对象之间通过反射拷贝数据

/// <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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值