C# 对象克隆 TOut ObjectHelper.Clone<TIn, TOut>
使用方法
C# 全选
ObjectHelper.Clone<tb_MyUser, ModelUser>(result);
ObjectHelper.cs
C# 全选
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace CSFramework.WebApi.Utils
{
/// <summary>
/// 对象操作类
/// </summary>
public static class ObjectHelper
{
/// <summary>
/// 复制对象, 仅复制对象相同属性的值.
/// </summary>
/// <param name="source">对象实例</param>
/// <param name="ignoreCase">对象属性名称匹配忽略大小写</param>
/// <returns></returns>
public static TOut Clone<TIn, TOut>(TIn source, bool ignoreCase = true)
{
try
{
if (source == null) return default(TOut);
Type objTypeIn = typeof(TIn);
Type objTypeOut = typeof(TOut);
PropertyInfo[] propsIn = objTypeIn.GetProperties();
PropertyInfo[] propsOut = objTypeOut.GetProperties();
//返回的对象实例
TOut destObj = (TOut)objTypeOut.Assembly.CreateInstance(objTypeOut.FullName);
foreach (PropertyInfo infoSource in propsIn)
{
object value = infoSource.GetValue(source, null);
//判断相同属性名称
var pTarget = propsOut.Where(w => String.Compare(w.Name, infoSource.Name, ignoreCase) == 0).FirstOrDefault();
if (pTarget != null)
SetPropertyValue(destObj, pTarget, value);
}
return destObj;
}
catch
{
return default(TOut);
}
}
/// <summary>
/// 给对象的属性赋值
/// </summary>
/// <param name="instance">对象实例</param>
/// <param name="prop">对象实例的属性信息</param>
/// <param name="value">其他对象属性的值</param>
public static void SetPropertyValue(object instance, PropertyInfo prop, object value)
{
try
{
if (prop == null) return;
if (prop.PropertyType.IsArray)//数组类型,单独处理
{
if (value == DBNull.Value)//特殊处理DBNull类型
prop.SetValue(instance, null, null);
else
prop.SetValue(instance, value, null);
}
else
{
if (value == null || String.IsNullOrWhiteSpace(value.ToString()))//空值
value = prop.PropertyType.IsValueType ? Activator.CreateInstance(prop.PropertyType) : null;//值类型
else
value = System.ComponentModel.TypeDescriptor.GetConverter(prop.PropertyType).ConvertFromString(value.ToString());//创建对象
prop.SetValue(instance, value, null);
}
}
catch (Exception ex)
{
//报错在此跟踪
}
}
}
}
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网