3

我为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;
  }
}

谢谢,丹奥

4

3 回答 3

1

I would just use ICollection and override Equals( object ) for your comparisons.

public class MyTargetType
{
    public override bool Equals( object obj )
    {
        return ( obj is MyTargetType )
                    ? this.ID == ( ( MyTargetType ) obj ).ID
                    : false;
    }
}

Then in your loop, you would match the object directly instead of using reflection.

var target = targetCollection.SingleOrDefault( x => x.Equals( o ) );
于 2011-05-03T04:48:09.560 回答
1

尽管我无法找到动态转换泛型集合的方法,但我确实找到了解决我试图解决的潜在问题的方法,即注入包含子集合的 EF POCO 对象(一对多“导航属性”)。

我刚刚从 EF 4.0 升级到 EF 4.1,哈利路亚!EF 4.1 现在实际上管理子集合上的对象合并。升级后,我可以按原样使用 CloneInjection。

于 2011-05-04T21:40:08.213 回答
0

我想这就是你要找的:

    public class M1
    {
        public string Name { get; set; }
    }

    public class M2
    {
        public string Name { get; set; }
    }

    [Test]
    public void Cast()
    {
        object source = new List<M1> {new M1 {Name = "o"}};
        object target = new List<M2>();


        var targetArgumentType = target.GetType().GetGenericArguments()[0];

        var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(targetArgumentType));
        var add = list.GetType().GetMethod("Add");

        foreach (var o in source as IEnumerable)
        {
            var t = Activator.CreateInstance(targetArgumentType);
            add.Invoke(list, new[] { t.InjectFrom(o) });
        }

        target = list;

        Assert.AreEqual("o", (target as List<M2>).First().Name);
    }

使用 .NET 4,您可以通过使用动态

于 2011-05-07T13:52:13.973 回答