C# Reflection - merge two objects together

前端 未结 2 1519
暗喜
暗喜 2020-12-20 01:51

I have a need to update object A\'s property if null with that from object B\'s equivalent property if that is not null. I wanted code I can use for various objects.

<
2条回答
  •  一生所求
    2020-12-20 02:14

    Hi I modified Ben Robinsons solution in order to not overwrite Collections or list, instead, it adds the elements of one object to the other one where the merging is happening:

     public static class ExtensionMethods
    {
        public static TEntity CopyTo(this TEntity OriginalEntity, TEntity EntityToMergeOn)
        {
            PropertyInfo[] oProperties = OriginalEntity.GetType().GetProperties();
    
            foreach (PropertyInfo CurrentProperty in oProperties.Where(p => p.CanWrite))
            {
                var originalValue = CurrentProperty.GetValue(EntityToMergeOn);
    
                if (originalValue != null)
                {
                    IListLogic(OriginalEntity, CurrentProperty, originalValue);
                }
                else
                {
                    var value = CurrentProperty.GetValue(OriginalEntity, null);
                    CurrentProperty.SetValue(EntityToMergeOn, value, null);
                }
            }
    
            return OriginalEntity;
        }
    
        private static void IListLogic(TEntity OriginalEntity, PropertyInfo CurrentProperty, object originalValue)
        {
            if (originalValue is IList)
            {
                var tempList = (originalValue as IList);
                var existingList = CurrentProperty.GetValue(OriginalEntity) as IList;
    
                foreach (var item in tempList)
                {
                    existingList.Add(item);
                }
    
            }
        }
    }
    

提交回复
热议问题