2011-10-28 39 views
1

我們有一個自定義對象擴展方法來處理以下內容。從遺產轉移到ValueInjecter

  • 來源是DataRow目標是class
  • 來源是DataTable目標是List<class>
  • 來源是class目標是class
  • 來源是List<class>目標是List<class>

我發現ValueInjecter and DataTable這樣我就可以處理一個DataRow和DataTable。
所以,我要將它粘在一起。

這是我試過的。

public static class ObjectExtensions 
{ 
    public static void OldFill(this object fillMe, object sourceObject) 
    { 
     Type sourceType = sourceObject.GetType(); 
     Type fillType = fillMe.GetType(); 

     switch (sourceType.Name) 
     { 
      case "DataRow": 
       fillMe.InjectFrom<DataRowInjection>(sourceObject); 
       break; 

      case "DataTable": 
       fillMe.InjectFrom<DataTableInjection<fillType>>(sourceObject); 
       break; 

      default: 
       fillMe.InjectFrom(sourceObject); 
       break; 
     } 
    } 
} 

不確定如何獲得正確的fillType使代碼正常工作。
因爲這是遺留代碼,我不想更改擴展簽名。

回答

1

我不知道答案,但我可以說DataTableInjection<fillType>不會編譯。您需要使用Reflection來執行綁定,如下所示:

case "DataTable": 
    var tableInjector = typeof (DataTableInjection<>).MakeGenericType(fillType); 
    tableInjector.GetMethod("InjectFrom").MakeGenericMethod(tableInjector) 
    .Invoke(fillMe, new[] { sourceObject }); 
    break;