我为ValueInjecter创建了一个自定义注入类,它为通用子集合进行递归注入,但它适用于现有的目标对象,而不是像 VI 站点上的“CloneInjection”示例那样进行克隆。但是,目前我正在转换为已知类型 (ICollection<MyTargetType>),因此注入类仅适用于一种硬编码类型。我似乎无法找到一种动态投射泛型的方法,有什么建议吗?这是我的“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;
}
}
谢谢,丹奥