您的位置:首页 > 编程语言 > C#

反射实现深拷贝

2016-07-13 09:55 549 查看
源代码引用自: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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反射 深拷贝 C#