ジェネリック子コレクションの再帰的注入を行うValueInjecterのカスタム注入クラスを作成しましたが、VI サイトの「CloneInjection」サンプルのように複製するのではなく、既存のターゲット オブジェクトで動作します。ただし、現在、既知の型 (ICollection<MyTargetType>) にキャストしているため、インジェクション クラスはハード コードされた 1 つの型にのみ適しています。ジェネリックを動的にキャストする方法を理解できないようですが、何か提案はありますか? 「RecursiveInjection」クラスの SetValue コードは次のとおりです。
//for value types and string just return the value as is
if (c.SourceProp.Type.IsValueType || c.SourceProp.Type == typeof(string))
return c.SourceProp.Value;
if (c.SourceProp.Type.IsGenericType)
{
//handle IEnumerable<> also ICollection<> IList<> List<>
if (c.SourceProp.Type.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable)))
{
var t = c.TargetProp.Type.GetGenericArguments()[0];
if (t.IsValueType || t == typeof(string)) return c.SourceProp.Value;
//get enumerable object in target
var targetCollection = c.TargetProp.Value as ICollection<MyTargetType>;
//possible to cast dynamically?
foreach (var o in c.SourceProp.Value as IEnumerable)
{
//get ID of source object
var sourceID = (int)o.GetProps().GetByName("ID").GetValue(o);
//find matching target object if there is one
var target = targetCollection.SingleOrDefault(x => x.ID == sourceID);
if (target != null)
{
target.InjectFrom<RecursiveInjection>(o);
}
}
return targetCollection;
}
}
ありがとう、DanO