源代码引用自:http://www.tuicool.com/articles/beu2InZ,做了一些修改,反射的时候直接取字段值,不取属性值,因为属性最终是暴漏的字段值。修改后的代码支持泛型。源代码泛型报错。
public static T DeepCopyWithReflection(T obj)
{
Type type = obj.GetType();
// 如果是字符串或值类型则直接返回
if (obj is string || type.IsValueType) return obj;
if (type.IsArray)
{
Type elementType = Type.GetType(type.FullName.Replace(“[]”, string.Empty));
var array = obj as Array;
Array copied = Array.CreateInstance(elementType, array.Length);
for (int i = 0; i < array.Length; i++)
{
if (array.GetValue(i) == null)
{
continue;
}
copied.SetValue(DeepCopyWithReflection(array.GetValue(i)), i);
}
return (T)Convert.ChangeType(copied, obj.GetType());
}
object retval = Activator.CreateInstance(obj.GetType());
FieldInfo[] fields = obj.GetType().GetFields(
BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.Static);
foreach (var field in fields)
{
if (field.IsLiteral || field.IsInitOnly)//常量或只读变量排除
{
continue;
}
var propertyValue = field.GetValue(obj);
if (propertyValue == null)
continue;
field.SetValue(retval, DeepCopyWithReflection(propertyValue));
}
return (T)retval;
}
反射实现深拷贝
最新推荐文章于 2021-02-24 18:06:34 发布