我有一个方法,我传入两个具有相同属性名称的对象,并且我使用反射从一个对象获取值并在另一个对象上设置值。我的问题是,当我遇到一个作为集合的属性时,原始属性是 EntityCollection,而设置的属性是 ObservableCollection,当我尝试设置值时,我显然会抛出一个转换错误。
那么我该怎么做呢?我认为一种方法是获取 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);
}
}
}