2010-12-28 12 views
5

Uso un controllo di terze parti che esporta alcuni dati in formati diversi. Il controllo ha una proprietà ExportSettings. Ma è di sola lettura.Enumerazione e copia delle proprietà da un oggetto a un altro oggetto dello stesso tipo

ho per impostare manualmente le sue proprietà come

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

Così mi vengono i ExportSettings oggetto da parte dell'utente e voglio impostarlo al controllo.

Come posso copiare tutti i suoi valori membro nel controllo utente?

risposta

18

Try riflessione a base di clonazione:

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

È possibile farlo tramite Reflection.

Qualcosa di simile a questo:

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)); 
    } 
    } 
Problemi correlati