複製物件裡的值

  • 4270
  • 0
  • 2017-07-27

摘要:複製物件裡的值

準備來源與目標物件,複製依據Property Name相同時才複製其值

        public void copy_data(object source, object dest)
        {
            PropertyDescriptorCollection sourceProps =
                               TypeDescriptor.GetProperties(source),
                   destProps = TypeDescriptor.GetProperties(dest);
            foreach (PropertyDescriptor prop in sourceProps)
            {
                PropertyDescriptor destProp = destProps[prop.Name];
                try
                {
                    if (destProp != null) destProp.SetValue(dest, prop.GetValue(source));
                }
                catch (Exception e)
                {
                    throw new Exception(prop.Name + ":" + e.Message);
                }
            }
        }

 


TonyHuang