簡體   English   中英

Linq查詢從對象B獲取具有相同名稱和對象類型A的屬性

[英]Linq query to get the properties from object B which have the same name and type of object A

我正處於一個互操作場景,因為我正在處理結構和類使用類似於不同程序集中的結構 - 所以演員是不夠的,必須手動逐場進行,這是非常無聊和容易出錯。

所以我設計了一個復制大量簡單字段/屬性的函數,我只處理有問題的字段/屬性。

當我只對屬性執行此操作時,它可以正常工作。 但我現在需要如何修復此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個不同的匿名類型,因為其中一個具有名為FieldType的屬性,另一個具有名為PropertyType 除非兩個類型具有完全相同的完全相同的字段,否則LINQ無法進行連接。 在燈架上有一個精彩的文章在這里找到

在這種情況下,您需要為您的加入執行此操作:

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

我想你可能會在AutoMapper之后。 http://automapper.codeplex.com/或Value Injector 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM