Linq查询从对象B获取具有相同名称和对象类型A的属性

时间:2013-02-22 23:30:42

标签: c# .net linq reflection

我正处于互操作场景中,因为我正在处理结构和类,就像在不同的程序集中使用结构一样 - 所以演员阵容是不够的,必须手动逐场进行,这非常无聊并且容易出错。

所以我设计了一个复制大量简单字段/属性的函数,我只处理那些陷入困境的函数。

当我只对属性执行此操作时,它可以正常工作。但我现在需要如何解决这个LiNQ查询,以便能够从源对象中获取字段列表,并将它们与目标对象上的属性连接起来。

以下代码:

    var TypeOrig = pSource.GetType();
    var TypeDest = pTarget.GetType();
    var TypeString = typeof(System.String);

    var PropOrig = TipoOrig.GetFields(); // if it is GetProperties instead 
                                         // of GetFields works OK
    var PropDest = TipoDest.GetProperties();

    var QryPropVT =
      from
        POrig in PropOrig
      join PDest in PropDest
        on new
        {
            POrig.Name,
            POrig.FieldType
        } equals new
        {
            PDest.Name,
            PDest.PropertyType
        }
      where POrig.PropertyType.IsValueType || (POrig.PropertyType.Equals(TipoString))
      select new
      {
          PropO = POrig,
          PropD = PDest
      };

Visual C# error: Error 2 The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'.

编辑:我看到价值注入器,但就像使用死星杀死蚊子一样...... [/编辑]

2 个答案:

答案 0 :(得分:3)

您的连接语句似乎创建了两种不同的匿名类型,因为其中一个属性名为FieldType,另一个属性名为PropertyType。除非两个类型具有完全相同的完全相同的字段,否则LINQ无法进行连接。有一篇关于这个found here的精彩文章。

在这种情况下,您需要为您的加入执行此操作:

join PDest in PropDest
        on new
        {
            Name = POrig.Name,
            JoinType = POrig.FieldType
        } equals new
        {
            Name = PDest.Name,
            JoinType = PDest.PropertyType
        }

答案 1 :(得分:1)

我想你可能会在AutoMapper之后。 http://automapper.codeplex.com/或价值注入者http://valueinjecter.codeplex.com/

价值注入者示例:

myObject.InjectFrom(anyOtherObject);

//inject from multiple sources
a.InjectFrom(b,c,d,e);

//inject using your own injection
a.InjectFrom<MyInjection>(b);
相关问题