C# Reflection - merge two objects together

前端 未结 2 1520
暗喜
暗喜 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:33

    I have created the below extension method for use in my latest project and it works fine, collections and all. It is a pretty much a simpler version of what you are doing in your method. With mine both classes have to be the same type. What problem do you encounter with collections?

        public static class ExtensionMethods
        {
            public static TEntity CopyTo(this TEntity OriginalEntity, TEntity NewEntity)
            {
                PropertyInfo[] oProperties = OriginalEntity.GetType().GetProperties();
    
                foreach (PropertyInfo CurrentProperty in oProperties.Where(p => p.CanWrite))
                {
                    if (CurrentProperty.GetValue(NewEntity, null) != null)
                    {
                        CurrentProperty.SetValue(OriginalEntity, CurrentProperty.GetValue(NewEntity, null), null);
                    }
                }
    
                return OriginalEntity;
            }
        }
    

提交回复
热议问题