2010-12-28 10 views
5

Utilizo un control de terceros que exporta algunos datos a diferentes formatos. El control tiene una propiedad ExportSettings. Pero es de solo lectura.Enumerar y copiar propiedades de un objeto a otro del mismo tipo

he para establecer manualmente sus propiedades como

ctrl.ExportSettings.Paging = false; 
ctr.ExportSettings.Background = Color.Red; 

Así que tengo los ExportSettings objeto por parte del usuario y quiero ponerlo en el control.

¿Cómo puedo copiar todos sus valores de miembro en el control de usuario?

Respuesta

18

Try basada en la reflexión clonación:

private object CloneObject(object o) 
{ 
    Type t = o.GetType(); 
    PropertyInfo[] properties = t.GetProperties(); 

    Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, 
     null, o, null); 

    foreach (PropertyInfo pi in properties) 
    { 
     if (pi.CanWrite) 
     { 
      pi.SetValue(p, pi.GetValue(o, null), null); 
     } 
    } 

    return p; 
} 
1

Puede hacerlo a través de Reflection.

Algo como esto:

Type exportSettingType = ctrl.ExportSettings.GetType(); 

foreach (PropertyInfo property in exportSettingType.GetProperties()) 
{ 
    object value = property.GetValue(ctrl.ExportSettings, null); 
    property.SetValue(secondControl.ExportSettings, value, null); 
} 
16
static void CopyProperties(object dest, object src) 
    { 
    foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src)) 
    { 
    item.SetValue(dest, item.GetValue(src)); 
    } 
    } 
Cuestiones relacionadas