我有一個方法,我傳遞兩個對象,它們具有相同的屬性名稱,我使用Reflection從一個對象獲取值並在另一個對象上設置值。我遇到的問題是,當我遇到一個屬性是一個集合,原始的是EntityCollection,設置的是ObservableCollection,當我嘗試設置值時,我顯然會拋出一個轉換錯誤。如何在ICollection類型的屬性上使用反射?
那麼我會怎麼做呢?我認爲一種方法是獲取EntityCollection屬性的實例,並在循環中使用Activator.CreateInstance()向ObservableCollection添加一個新項目。但是我遇到了另一個如何獲得原始實例的問題。
我會非常感謝這個困境的一些見解。我將發佈我正在使用的方法的代碼。目前它不工作,主要是我發佈它僅供參考。所以請不要指出明顯的。提前致謝。
protected void SetValues(Object thisObject, Object entity)
{
PropertyInfo[] properties = entity.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
var value = property.GetValue(entity, null);
var thisObjectsProperty = thisObject.GetType().GetProperty(property.Name);
if (thisObjectsProperty != null && value != null)
{
if (thisObjectsProperty.PropertyType.GetInterface("ICollection", true) != null && thisObjectsProperty.PropertyType.GetGenericArguments().Count() > 0)
{
Type genericType = thisObjectsProperty.PropertyType.GetGenericArguments()[0];
Type entityCollectionType = property.PropertyType;
Type thisCollectionType = thisObjectsProperty.PropertyType;
IList entityCollection = (IList)Activator.CreateInstance(entityCollectionType.MakeGenericType(genericType));
IList observableCollection = (IList)Activator.CreateInstance(thisCollectionType.MakeGenericType(genericType));
foreach (var item in entityCollection)
{
String typeString = String.Concat("RulesGenerator.DependencyObjects.", genericType.Name);
Type newItemType = Type.GetType(typeString, false, true);
if (newItemType != null)
{
var newItem = Activator.CreateInstance(newItemType);
SetValues(newItem, item);
observableCollection.Add(newItem);
}
}
}
else
thisObjectsProperty.SetValue(thisObject, value, null);
}
}
}
是有一些原因,你不能只克隆對象? – eschneider 2010-10-28 14:42:21
從未嘗試過克隆,我會盡力回覆你。謝謝。 – jhorton 2010-10-28 16:38:31