如何将属性从一个对象复制到另一个具有不同值C#的对象



我想将给定对象ClassA中Properties的值复制到另一个名为ClassB的对象实例,这些类可能是同一类型,也可能不是同一类型。

如果ClassB中的属性有一个值,而ClassA中相应的属性值为null,则不要复制该值,所以只复制ClassB中当前属性为null的地方。

这不是一个克隆练习,目标对象(ClassB)已经用部分定义的值实例化,我正在寻找一种可重复使用的方法来复制尚未设置的其余值。

想想测试场景,我们有一个通用或默认的测试数据值,对于特定的测试,我想设置一些特定的字段,然后从通用测试数据对象中完成其他属性的设置。

我想我正在寻找一个基于反射的解决方案,因为这样我们就不需要知道要复制的特定类型,这将使其可用于许多不同的场景。

例如。

public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public Address ContactAddress { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}

测试,例如

public void TestMethod1()
{
Employee employee = new Employee();
employee.EmployeeID = 100;
employee.EmployeeName = "John";
employee.ContactAddress = new Address();
employee.ContactAddress.Address1 = "Park Ave";
employee.ContactAddress.City = "New York";
employee.ContactAddress.State = "NewYork";
employee.ContactAddress.ZipCode = "10002";

Employee employeeCopy = new Employee();
employeeCopy.EmployeeID = 101;
employeeCopy.EmployeeName = "Tom";
employeeCopy.ContactAddress = new Address();
CopyPropertiesTo(employee, employeeCopy);
}

我想得到的结果

employeeCopy EmployeeID=101
EmployeeName="汤姆
ContactAddress.Address1="Park Ave">
ContactAddress.City="纽约">
ContactAddress.State="纽约">
ContactAddress.ZipCode="10002〃;

因此,在这种情况下,由于employeeCopy.ContactAddress中没有设置任何字段,因此只应跨复制原始employee对象中的那些字段。

我不知道如何编写方法:
CopyPropertiesTo(object sourceObject, object targetObject)

实现这一点的一种方法是简单地检查"至";Employee,如果它是null0,则将";从";Employee:

/// <summary>
/// Copies values in 'from' to 'to' if they are null in 'to'
/// </summary>
public static void CopyProperties(Employee from, Employee to)
{
if (from == null) return;
if (to == null) to = new Employee();
if (to.EmployeeID == 0) to.EmployeeID = from.EmployeeID;
if (to.EmployeeName == null) to.EmployeeName = from.EmployeeName;
if (from.ContactAddress == null) return;
if (to.ContactAddress == null) to.ContactAddress = new Address();
if (to.ContactAddress.Address1 == null)
to.ContactAddress.Address1 = from.ContactAddress.Address1;
if (to.ContactAddress.City == null)
to.ContactAddress.City = from.ContactAddress.City;
if (to.ContactAddress.State == null)
to.ContactAddress.State = from.ContactAddress.State;
if (to.ContactAddress.ZipCode == null)
to.ContactAddress.ZipCode = from.ContactAddress.ZipCode;
}

如果不算太晚,这里也是我的建议,但可能会有所帮助。

public class Source
{
[DefaultValueAttribute(-1)]
public int Property { get; set; }
public int AnotherProperty { get; set; }
}
public class Dedstination
{
public int Property { get; set; }
[DefaultValueAttribute(42)]
public int AnotherProperty { get; set; }
}
public void Main()
{
var source = new Source { Property = 10, AnotherProperty = 76 };
var destination = new Dedstination();
MapValues(source, destination);
}
public static void MapValues<TS, TD>(TS source, TD destination)
{
var srcPropsWithValues = typeof(TS)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToDictionary(x => x.Name, y => y.GetValue(source));
var dstProps = typeof(TD)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToDictionary(key => key, value => value.GetCustomAttribute<DefaultValueAttribute>()?.Value
?? (value.PropertyType.IsValueType
? Activator.CreateInstance(value.PropertyType, null)
: null));
foreach (var prop in dstProps)
{
var destProperty = prop.Key;
if (srcPropsWithValues.ContainsKey(destProperty.Name))
{
var defaultValue = prop.Value;
var currentValue = destProperty.GetValue(destination);
var sourceValue = srcPropsWithValues[destProperty.Name];
if (currentValue.Equals(defaultValue) && !sourceValue.Equals(defaultValue))
{
destProperty.SetValue(destination, sourceValue);
}
}
}
}

编辑:我编辑了我的解决方案,以消除对使用DefaultValueAttribute的依赖。现在,您可以从指定的属性或默认类型中获取默认值。

以前的解决方案如下:

// This solution do not needs DefaultValueAttributes 
var dstProps = typeof(TD)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToDictionary(x => x, x => x.PropertyType.IsValueType ? Activator.CreateInstance(x.PropertyType, null) : null);
// This solution needs DefaultValueAttributes 
var dstProps = typeof(TD)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.ToDictionary(x => x, x => x.GetCustomAttribute<DefaultValueAttribute>()?.Value ?? null);

深度克隆可以通过序列化轻松实现,但只在非null字段之间复制需要更多的条件逻辑。在这种情况下,我将其称为Coalesce,因此我将方法命名为CoalesceTo。如果愿意,可以将其重构为一个扩展方法,但我不建议这样做,而是将其放在一个静态助手类中。尽管这可能很有用,但我不鼓励你这样做;goto;用于生产业务运行时。

对这些类型的解决方案使用Reflection通常是效率最高的机制,但它给了我们很大的灵活性,非常适合模拟、原型设计和快速单元测试表达式。

  • 尽管不在本例中,但对于高级场景,添加检查以排除[Obsolete]属性是很容易的

以下示例使用属性名称比较,因此不必传入相同类型的对象。请注意,创建了IsNullIsValueType方法来封装这些概念,从而简化了您可能想要对该方法进行的调整。

  • 此方法还检查在继续之前是否可以读取/写入属性,这允许我们支持源对象上的只读属性,当然我们不会尝试写入只读属性
  • 最终的值解析和写入被封装在一个try-catch语句中,该语句可以抑制任何错误。要使这样的代码通用,需要进行一些调整,但对于简单的类型定义,它应该可以正常工作
/// <summary>
/// Deep Copy the top level properties from this object only if the corresponding property on the target object IS NULL.
/// </summary>
/// <param name="source">the source object to copy from</param>
/// <param name="target">the target object to update</param>
/// <returns>A reference to the Target instance for chaining, no changes to this instance.</returns>
public static void CoalesceTo(object source, object target, StringComparison propertyComparison = StringComparison.OrdinalIgnoreCase)
{
var sourceType = source.GetType();
var targetType = target.GetType();
var targetProperties = targetType.GetProperties();
foreach(var sourceProp in sourceType.GetProperties())
{
if(sourceProp.CanRead)
{
var sourceValue = sourceProp.GetValue(source);
// Don't copy across nulls or defaults
if (!IsNull(sourceValue, sourceProp.PropertyType))
{
var targetProp = targetProperties.FirstOrDefault(x => x.Name.Equals(sourceProp.Name, propertyComparison));
if (targetProp != null && targetProp.CanWrite)
{
if (!targetProp.CanRead)
continue; // special case, if we cannot verify the destination, assume it has a value.
else if (targetProp.PropertyType.IsArray || targetProp.PropertyType.IsGenericType // It is ICollection<T> or IEnumerable<T>
&& targetProp.PropertyType.GenericTypeArguments.Any()
&& targetProp.PropertyType.GetGenericTypeDefinition() != typeof(Nullable<>) // because that will also resolve GetElementType!
)
continue; // special case, skip arrays and collections...
else
{
// You can do better than this, for now if conversion fails, just skip it
try
{
var existingValue = targetProp.GetValue(target);
if (IsValueType(targetProp.PropertyType))
{
// check that the destination is NOT already set.
if (IsNull(existingValue, targetProp.PropertyType))
{
// we do not overwrite a non-null destination value
object targetValue = sourceValue;
if (!targetProp.PropertyType.IsAssignableFrom(sourceProp.PropertyType))
{
// TODO: handle specific types that don't go across.... or try some brute force type conversions if neccessary
if (targetProp.PropertyType == typeof(string))
targetValue = targetValue.ToString();
else 
targetValue = Convert.ChangeType(targetValue, targetProp.PropertyType);
}
targetProp.SetValue(target, targetValue);
}
}
else if (!IsValueType(sourceProp.PropertyType))
{
// deep clone
if (existingValue == null)
existingValue = Activator.CreateInstance(targetProp.PropertyType);
CoalesceTo(sourceValue, existingValue);
}
}
catch (Exception)
{
// suppress exceptions, don't set a field that we can't set
}
}
}
}
}
}
}
/// <summary>
/// Check if a boxed value is null or not
/// </summary>
/// <remarks>
/// Evaluate your own logic or definition of null in here.
/// </remarks>
/// <param name="value">Value to inspect</param>
/// <param name="valueType">Type of the value, pass it in if you have it, otherwise it will be resolved through reflection</param>
/// <returns>True if the value is null or primitive default, otherwise False</returns>
public static bool IsNull(object value, Type valueType = null)
{
if (value is null)
return true;
if (valueType == null) valueType = value.GetType();
if (valueType.IsPrimitive || valueType.IsEnum || valueType.IsValueType)
{
// Handle nullable types like float? or Nullable<Int>
if (valueType.IsGenericType)
return value is null;
else
return Activator.CreateInstance(valueType).Equals(value);
}
// treat empty string as null!
if (value is string s)
return String.IsNullOrWhiteSpace(s);
return false;
}
/// <summary>
/// Check if a type should be copied by value or if it is a complexe type that should be deep cloned
/// </summary>
/// <remarks>
/// Evaluate your own logic or definition of Object vs Value/Primitive here.
/// </remarks>
/// <param name="valueType">Type of the value to check</param>
/// <returns>True if values of this type can be straight copied, false if they should be deep cloned</returns>
public static bool IsValueType(Type valueType)
{
// TODO: any specific business types that you want to treat as value types?
// Standard .Net Types that can be treated as value types
if (valueType.IsPrimitive || valueType.IsEnum || valueType.IsValueType || valueType == typeof(string))
return true;
// Support Nullable Types as Value types (Type.IsValueType) should deal with this, but just in case
if (valueType.HasElementType // It is array/enumerable/nullable
&& valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Nullable<>))
return true;

return false;
}

因为我们在这里使用反射,我们无法利用Generics可以为我们提供的优化。如果您想将其适应生产环境,请考虑使用T4模板来编写此逻辑的Generic类型版本,作为您业务类型的扩展方法。

深度克隆-

你会注意到我特别跳过了数组和其他IEnumerable结构。。。支持它们的蠕虫有很多,最好不要让一个方法尝试Deep复制,所以去掉对CoalesceTo的嵌套调用,然后在树中的每个对象上调用克隆方法。

数组/集合/列表的问题在于,在克隆之前,您需要确定一种方法,使源中的集合与目标中的集合同步,您可以根据Id字段或某种属性(如[KeyAttribute])制定一个约定,但这种实现需要高度特定于您的业务逻辑,并且不在本篇文章的范围内;)

DecimalDateTime这样的类型在这些类型的场景中是有问题的,不应该将它们与null进行比较,相反,我们必须将它们与它们的默认类型状态进行比较,在这种情况下,我们不能使用通用的default运算符或值,因为该类型只能在运行时解析。

因此,我更改了您的类,以包含DateTimeOffset如何由以下逻辑处理的示例:

public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public DateTimeOffset Date { get; set; }
public float? Capacity { get; set; }
Nullable<int> MaxShift { get; set; }
public Address ContactAddress { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}
public static  void TestMethod1()
{
Employee employee = new Employee();
employee.EmployeeID = 100;
employee.EmployeeName = "John";
employee.Capacity = 26.2f;
employee.MaxShift = 8;
employee.Date = new DateTime(2020,1,22);
employee.ContactAddress = new Address();
employee.ContactAddress.Address1 = "Park Ave";
employee.ContactAddress.City = "New York";
employee.ContactAddress.State = "NewYork";
employee.ContactAddress.ZipCode = "10002";
Employee employeeCopy = new Employee();
employeeCopy.EmployeeID = 101;
employeeCopy.EmployeeName = "Tom";
employeeCopy.ContactAddress = new Address();
CoalesceTo(employee, employeeCopy);
}

这将产生以下对象图:

{
"EmployeeID": 101,
"EmployeeName": "Tom",
"Date": "2020-01-22T00:00:00+11:00",
"Capacity":26.2,
"MaxShift":8,
"ContactAddress": {
"Address1": "Park Ave",
"City": "New York",
"State": "NewYork",
"ZipCode": "10002"
}
}

在复制完成和/或实现ICloneable接口后,对新实例进行更改。https://learn.microsoft.com/en-us/dotnet/api/system.icloneable?view=netcore-3.1

private Employee Check(Employee employee,Employee employeeCopy)
{
if (employeeCopy.EmployeeID==0 && employee.EmployeeID !=0)
{
employeeCopy.EmployeeID = employee.EmployeeID;
}
if (employeeCopy.EmployeeName == null && employee.EmployeeName != null)
{
employeeCopy.EmployeeName = employee.EmployeeName;
}
if (employeeCopy.ContactAddress == null)
{
if (employeeCopy.ContactAddress.Address1 == null && employee.ContactAddress.Address1 != null)
{
employeeCopy.ContactAddress.Address1 = employee.ContactAddress.Address1;
}
if (employeeCopy.ContactAddress.City == null && employee.ContactAddress.City != null)
{
employeeCopy.ContactAddress.City = employee.ContactAddress.City;
}
if (employeeCopy.ContactAddress.State == null && employee.ContactAddress.State != null)
{
employeeCopy.ContactAddress.State = employee.ContactAddress.State;
}
if (employeeCopy.ContactAddress.ZipCode == null && employee.ContactAddress.ZipCode != null)
{
employeeCopy.ContactAddress.ZipCode = employee.ContactAddress.ZipCode;
}
}
return employeeCopy;
}

这就是你要找的吗?

public static void CopyPropertiesTo(Employee EP1, Employee EP2){

Type eType=typeof(Employee);
PropertyInfo[] eProps = eType.GetProperties();
foreach(var p in eProps){
if(p.PropertyType != typeof(String) && p.PropertyType != typeof(Int32)){
//Merging Contact Address
Type cType=p.PropertyType;
PropertyInfo[] cProps = cType.GetProperties();

foreach(var c in cProps){
//Check if value is null
if (String.IsNullOrEmpty((EP2.ContactAddress.GetType().GetProperty(c.Name).GetValue(EP2.ContactAddress) as string))){
//Assign Source to Target
EP2.ContactAddress.GetType().GetProperty(c.Name).SetValue(EP2.ContactAddress, (EP1.ContactAddress.GetType().GetProperty(c.Name).GetValue(EP1.ContactAddress)));
}
}
}
else{
//Check if value is null or empty
if (String.IsNullOrEmpty((EP2.GetType().GetProperty(p.Name).GetValue(EP2) as string))){
//Assign Source to Target
EP2.GetType().GetProperty(p.Name).SetValue(EP2, (EP1.GetType().GetProperty(p.Name).GetValue(EP1)));
}
}
}
}

不是最漂亮的,但这应该可以做到,并允许您更改类中属性的名称/数量。我从来没有真正尝试过这样做,所以如果有人有一些反馈,我会很感激

查看以下链接以获取更多信息和示例PropertyInfoGetTypeGetProperty

如果您先进行完整的深度克隆,然后设置您的值,那么这些类型的问题通常会更容易,资源占用更少。

SO上有很多关于深度克隆的帖子,我更喜欢使用JSON.Net进行序列化,然后进行反序列化。

public static T Clone<T>(T value, Newtonsoft.Json.JsonSerializerSettings settings = null)
{
var objectType = value.GetType();
var cereal = Newtonsoft.Json.JsonConvert.SerializeObject(value, settings);
return (T)Newtonsoft.Json.JsonConvert.DeserializeObject(cereal, objectType, settings);
}

但是,此代码需要Newtonsoft.Json-nuget包引用。

克隆对象首先设置所有公共/默认值,然后我们只修改此特定测试或代码块所需的属性。

public void TestMethod1()
{
Employee employee = new Employee();
employee.EmployeeID = 100;
employee.EmployeeName = "John";
employee.ContactAddress = new Address();
employee.ContactAddress.Address1 = "Park Ave";
employee.ContactAddress.City = "New York";
employee.ContactAddress.State = "NewYork";
employee.ContactAddress.ZipCode = "10002";

// Create a deep clone of employee
Employee employeeCopy = Clone(employee);
// set the specific fields that we want to change
employeeCopy.EmployeeID = 101;
employeeCopy.EmployeeName = "Tom";
}

通常,如果我们愿意改变我们的方法,我们可以找到更简单的解决方案,这个解决方案将具有与我们有条件地跨属性值复制相同的输出,但不进行任何比较。

如果你有其他原因需要条件复制,在本篇文章的其他解决方案中称为合并联合,那么我的另一个使用反射的答案可以完成任务,但它不如这个强大。

[TestClass]
public class UnitTest11
{
[TestMethod]
public void TestMethod1()
{
Employee employee = new Employee();
employee.EmployeeID = 100;
employee.EmployeeName = "John";
employee.Date = DateTime.Now;
employee.ContactAddress = new Address();
employee.ContactAddress.Address1 = "Park Ave";
employee.ContactAddress.City = "New York";
employee.ContactAddress.State = "NewYork";
employee.ContactAddress.ZipCode = "10002";
Employee employeeCopy = new Employee();
employeeCopy.EmployeeID = 101;
employeeCopy.EmployeeName = "Tom";
employeeCopy.ContactAddress = new Address();
employeeCopy.ContactAddress.City = "Bei Jing";
//copy all properties from employee to employeeCopy
CoalesceTo(employee, employeeCopy);
Console.ReadLine();
}
/// Deep Copy the top level properties from this object only if the corresponding property on the target object IS NULL.
/// </summary>
/// <param name="source">the source object to copy from</param>
/// <param name="target">the target object to update</param>
/// <returns>A reference to the Target instance for chaining, no changes to this instance.</returns>
public static void CoalesceTo(object source, object target, StringComparison propertyComparison = StringComparison.OrdinalIgnoreCase)
{
var sourceType = source.GetType();
var targetType = target.GetType();
var targetProperties = targetType.GetProperties();
foreach (var sourceProp in sourceType.GetProperties())
{
if (sourceProp.CanRead)
{
var sourceValue = sourceProp.GetValue(source);
// Don't copy across nulls or defaults
if (!IsNull(sourceValue, sourceProp.PropertyType))
{
var targetProp = targetProperties.FirstOrDefault(x => x.Name.Equals(sourceProp.Name, propertyComparison));
if (targetProp != null && targetProp.CanWrite)
{
if (!targetProp.CanRead)
continue; // special case, if we cannot verify the destination, assume it has a value.
else if (targetProp.PropertyType.IsArray || targetProp.PropertyType.IsGenericType // It is ICollection<T> or IEnumerable<T>
&& targetProp.PropertyType.GenericTypeArguments.Any()
&& targetProp.PropertyType.GetGenericTypeDefinition() != typeof(Nullable<>) // because that will also resolve GetElementType!
)
continue; // special case, skip arrays and collections...
else
{
// You can do better than this, for now if conversion fails, just skip it
try
{
var existingValue = targetProp.GetValue(target);
if (IsValueType(targetProp.PropertyType))
{
// check that the destination is NOT already set.
if (IsNull(existingValue, targetProp.PropertyType))
{
// we do not overwrite a non-null destination value
object targetValue = sourceValue;
if (!targetProp.PropertyType.IsAssignableFrom(sourceProp.PropertyType))
{
// TODO: handle specific types that don't go across.... or try some brute force type conversions if neccessary
if (targetProp.PropertyType == typeof(string))
targetValue = targetValue.ToString();
else
targetValue = Convert.ChangeType(targetValue, targetProp.PropertyType);
}
targetProp.SetValue(target, targetValue);
}
}
else if (!IsValueType(sourceProp.PropertyType))
{
// deep clone
if (existingValue == null)
existingValue = Activator.CreateInstance(targetProp.PropertyType);
CoalesceTo(sourceValue, existingValue);
}
}
catch (Exception)
{
// suppress exceptions, don't set a field that we can't set
}
}
}
}
}
}
}
/// <summary>
/// Check if a boxed value is null or not
/// </summary>
/// <remarks>
/// Evaluate your own logic or definition of null in here.
/// </remarks>
/// <param name="value">Value to inspect</param>
/// <param name="valueType">Type of the value, pass it in if you have it, otherwise it will be resolved through reflection</param>
/// <returns>True if the value is null or primitive default, otherwise False</returns>
public static bool IsNull(object value, Type valueType = null)
{
if (value is null)
return true;
if (valueType == null) valueType = value.GetType();
if (valueType.IsPrimitive || valueType.IsEnum || valueType.IsValueType)
return value.Equals(Activator.CreateInstance(valueType));
// treat empty string as null!
if (value is string s)
return String.IsNullOrWhiteSpace(s);
return false;
}
/// <summary>
/// Check if a type should be copied by value or if it is a complexe type that should be deep cloned
/// </summary>
/// <remarks>
/// Evaluate your own logic or definition of Object vs Value/Primitive here.
/// </remarks>
/// <param name="valueType">Type of the value to check</param>
/// <returns>True if values of this type can be straight copied, false if they should be deep cloned</returns>
public static bool IsValueType(Type valueType)
{
// TODO: any specific business types that you want to treat as value types?
// Standard .Net Types that can be treated as value types
if (valueType.IsPrimitive || valueType.IsEnum || valueType.IsValueType || valueType == typeof(string))
return true;
// Support Nullable Types as Value types (Type.IsValueType) should deal with this, but just in case
if (valueType.HasElementType // It is array/enumerable/nullable
&& valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Nullable<>))
return true;

return false;
}
}

public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public DateTimeOffset Date { get; set; }
public float? check { get; set; }
public Address ContactAddress { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
}

非常感谢每一个人,尤其是@Chris Schaller,我在上发布了代码

相关内容

最新更新