/// <summary> /// 子类重写此方法来实现更复杂的复制功能。 /// 默认使用反射进行对象的拷贝。 /// /// 注意: /// 集合字段,需要直接声明为 <![CDATA[IList<T>]]> 类型才能进行拷贝!!! /// </summary> /// <param name="target"></param> /// <param name="option"></param> protected virtual void CloneValues(Freezable target, CloneOption option) { var isFreeze = this._frozen; this._frozen = false; var allfields = this.EnumerateAllFileds(); foreach (var field in allfields) { if (field.HasMarked <NonSerializedAttribute>()) { continue; } var value = field.GetValue(target); //如果是引用对象,则进行深拷贝。 var freezable = value as Freezable; if (freezable != null) { if (option.DeepCloneRef) { value = freezable.Clone(option); } } //如果是子对象集合,则进行递归拷贝。 if (value is IList && option.CloneChildren) { var fieldValue = field.GetValue(this); if (fieldValue != null) { var myChildren = fieldValue as IList; if (myChildren == null) { throw new NotSupportedException("不支持不能转换为 IList 的字段" + field.Name); } if (!myChildren.IsReadOnly) { foreach (var item in value as IEnumerable) { var freeable = item as Freezable; if (freeable != null) { var newChild = freeable.Clone(option); myChildren.Add(newChild); } } } } continue; } field.SetValue(this, value); } this._frozen = isFreeze; }
protected Freezable Clone(CloneOption option) { Freezable target = null; if (!option.CopiedPairs.TryGetValue(this, out target)) { target = Activator.CreateInstance(this.GetType()) as Freezable; option.CopiedPairs[this] = target; target.CloneValues(this, option); } return(target); }