同じプロパティ名を持つ2つのオブジェクトを渡すメソッドがあり、Reflectionを使用して一方のオブジェクトから値を取得し、もう一方のオブジェクトに値を設定しています。私の問題は、コレクションであるプロパティに出くわしたとき、元のプロパティはEntityCollectionであり、設定されるのはObservableCollectionであり、値を設定しようとすると明らかにキャストエラーがスローされます。
では、これについてはどうすればよいでしょうか。1つの方法は、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);
}
}
}