cast class into another class or convert class to another

前端 未结 9 653
逝去的感伤
逝去的感伤 2020-11-28 22:29

my question is shown in this code

I have class like that

public class  maincs
{
  public int a;
  public int b;
  public int c;
  public int d; 
}
         


        
9条回答
  •  伪装坚强ぢ
    2020-11-28 22:57

    By using following code you can copy any class object to another class object for same name and same type of properties.

    public class CopyClass
    {
        /// 
        /// Copy an object to destination object, only matching fields will be copied
        /// 
        /// 
        /// An object with matching fields of the destination object
        /// Destination object, must already be created
        public static void CopyObject(object sourceObject, ref T destObject)
        {
            //  If either the source, or destination is null, return
            if (sourceObject == null || destObject == null)
                return;
    
            //  Get the type of each object
            Type sourceType = sourceObject.GetType();
            Type targetType = destObject.GetType();
    
            //  Loop through the source properties
            foreach (PropertyInfo p in sourceType.GetProperties())
            {
                //  Get the matching property in the destination object
                PropertyInfo targetObj = targetType.GetProperty(p.Name);
                //  If there is none, skip
                if (targetObj == null)
                    continue;
    
                //  Set the value in the destination
                targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
            }
        }
    }
    

    Call Method Like,

    ClassA objA = new ClassA();
    ClassB objB = new ClassB();
    
    CopyClass.CopyObject(objOfferMast, ref objB);
    

    It will copy objA into objB.

提交回复
热议问题