c#利用反射比较两个实体的差异,并把选中行的实例赋值给新的实例(要添加的实例)我所说的实例你可以当做是行
适用于与复制新增,或者复杂的复制新增主表和子表数据
/// <summary>
/// 复制新增
/// </summary>
/// <typeparam name="T1">实体1(传入一个新实例)</typeparam>
/// <typeparam name="T2">实体2(所复制的实例)</typeparam>
/// <param name="exclude">转换过程中过滤字段列表</param>
/// <returns></returns>
public static T1 DifferenceComparisonData<T1, T2>(T1 newInstance, T2 copyInstance, List<string> exclude) where T1 : class where T2 : class
{
if (true)
{
Type newType = newInstance.GetType();
Type currentType = copyInstance.GetType();
BindingFlags flags2 = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance;
PropertyInfo[] property1 = newType.GetProperties(flags2);
//排除主键和基础字段
//List<string> exclude = new List<string>() { "Id", "InsertTime", "UpdateTime", "DeleteTime", "Mark", "Version", "Code" };
foreach (PropertyInfo p in property1)
{
string name = p.Name;
if (exclude.Contains(name)) { continue; }
string newValue = p.GetValue(newInstance, null)?.ToString();
string currentValue = currentType.GetProperty(name)?.GetValue(copyInstance, null)?.ToString();
if (newValue != currentValue)
{
#region
//t1.GetField(p.Name).SetValue(t1.GetField(p.Name), value2);
//t1.GetField(p.Name).SetValue(t1,value2);
//value1 = t1.se;
//p.GetValue(source, null);
#endregion
newType.GetProperty(p.Name)?.SetValue(newInstance, p.GetValue(copyInstance, null), null);
}
}
return newInstance;
}
}