自定义 ValueInjecter 注入中的动态类型转换

发布于 2024-11-05 06:11:11 字数 1470 浏览 0 评论 0原文

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

谢谢,丹奥

I have created a custom injection class for ValueInjecter that does recursive injection for generic child collections, but that works with the existing target objects rather than cloning like the "CloneInjection" sample on the VI site. However, currently I am casting to a known type (ICollection<MyTargetType>), so the injection class is only good for the one hard coded type. I can't seem to figure a way to cast a generic dynamically, any suggestions? Here's the SetValue code for my "RecursiveInjection" class.

//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;
  }
}

Thanks, DanO

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泡沫很甜 2024-11-12 06:11:11

我只会使用 ICollection 并覆盖 Equals( object ) 进行比较。

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

然后在循环中,您将直接匹配对象,而不是使用反射。

var target = targetCollection.SingleOrDefault( x => x.Equals( o ) );

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 ) );
绅士风度i 2024-11-12 06:11:11

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

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

Although I haven't been able to figure a way to dynamically cast a generic collection, I did discover a solution to the underlying problem I was trying to solve, which was to inject EF POCO objects that contain child collections (one-to-many "navigation properties").

I just upgraded from EF 4.0 to EF 4.1, and hallelujah! EF 4.1 actually manages object merging on child collections now. After the upgrade, I am able to use the CloneInjection as is.

你げ笑在眉眼 2024-11-12 06:11:11

我认为这就是您正在寻找的:

    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,您可以通过使用动态使其变得更短

I think this is what you're looking for:

    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);
    }

with .NET 4 you can make this a bit shorter by using dynamic

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文