2010-05-31 64 views

回答

1

是的,你可以通過reflection來做到這一點。

閱讀這兩個實例的屬性並在反射的幫助下分配它們。

下面是一些代碼..

public static void AssignSourceToDestination(Object source, ref Object destination) 
    { 
     IList<PropertyInfo> sourceProps = source.GetProperties(); 
     IList<PropertyInfo> destProps = destination.GetProperties(); 

     foreach (PropertyInfo property in destProps) 
     { 
      if (property.CanWrite) 
      { 
       PropertyInfo sourceProp = sourceProps.Where(p => p.Name.Equals(property.Name) && 
        p.PropertyType.Equals(property.PropertyType) && p.CanRead).First(); 
       if (null != sourceProp) 
        property.SetValue(destination, sourceProp.GetValue(source, null), null); 
      } 
     } 
    } 

    public static IList<PropertyInfo> GetProperties(this Object me) 
    { 
     return me.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList(); 
    } 
相關問題