反射实现深拷贝
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;
}
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;
}
相关文章推荐
- Python动态类型的学习---引用的理解
- Java反射随记
- c#调用COM组件
- AS3中的反射(速记) 分析
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#实现给图片加水印的方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#中的delegate委托类型基本学习教程
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- 举例讲解C#中自动实现的属性
- C#中this的用法集锦
- C#数据结构之顺序表(SeqList)实例详解
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法