/// <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