2015-01-08 59 views
2

我需要創建對象的一個​​列表,其中的對象是從一個字符串.NET創建對象的列表,其中對象類型是從一個字符串

例如我想下面的方式轉換爲對象

Dim categoryList as IList(Of "classname") = new List(Of "class name") 

最終結果的列表

Dim categoryList As IList(Of BO.Store.Category) = New List(Of BO.Store.Category) 

感謝xxbbcc指着我在正確的方向。我想出了下面的解決方案,它可以讓我上傳任何csv文件並將其解析爲x對象列表。

這可以通過使用dropzone上傳文件以及表名,對象類名和映射類名來實現。這現在允許我使用csvhelper解析文件的內容,準備導入臨時表。

<AcceptVerbs(HttpVerbs.Post), BaseViewModelFilter> 
    Function Upload(model As ImportUploadViewModel) As JsonResult 

     Dim balUpload As BAL.Upload = New BAL.Upload() 
     Dim balImport As BAL.Import = New BAL.Import() 
     Dim folder As String = String.Format("{0}tmp\import\category", Server.MapPath("\")) 

     Dim result = balUpload.SaveFiles(Request, folder, UserProfile.ID) 

     Dim importClassType = Type.[GetType](String.Format("Roxybox.BO.{0}", model.EntityClass)) 
     Dim importClassMapType = Type.[GetType](String.Format("Roxybox.BO.{0}", model.EntityMap)) 

     Dim records As IList 

     ' Import all successful files 
     For Each successFile As String In result("success") 

      ' Parse csv file 
      Using sr = New StreamReader(String.Format("{0}\{1}", folder, successFile)) 
       Dim reader = New CsvReader(sr) 

       reader.Configuration.RegisterClassMap(importClassMapType) 
       records = reader.GetRecords(importClassType).ToList() 

      End Using 

      For Each category In records 
       Dim data As BO.Import = New BO.Import() 
       With data 
        .EntityModel = model.EntityModel 
        .Data = JsonConvert.SerializeObject(category) 
        .UserProfileID = UserProfile.ID 
        .Filename = successFile 
        .Status = "pending" 
       End With 

       balImport.Save(data, UserProfile.ID) 
      Next 
     Next 

     Return Json(result, JsonRequestBehavior.AllowGet) 

    End Function 

回答

1

您可以使用Activator.CreateInstance根據字符串程序集名稱/類型名稱創建對象。 (該方法還有許多其他過載。)

該調用返回Object,因此您必須將其轉換爲已知類型(例如,接口類型)。據我知道(我不是一個VB.Net專家)有沒有辦法來定義一個字符串類型名稱的變量,所以你要麼需要

  1. Store中的實例在Object -s名單(這可以工作,但你並沒有真正的可用對象)。
  2. 讓你的類型都實現通用的,衆所周知的接口。在這種情況下,您可以使用CreateInstance創建類型的實例,然後將它們轉換爲已知的接口類型。類型名稱將來自字符串,但接口類型必須硬編碼到代碼中。

例如(在C#):

List<IMyInterface> oList = new List<IMyInterface>(); 

    // ... 

    // Loop through your assembly/type names 
    ObjectHandle oHandle = Activator.CreateInstance(sAssemblyName, sTypeName); 
    IMyInterface oInstance = oHandle.Unwrap() as IMyInterface; // null if wrong type 

    if (oInstance!=null) 
     oList.Add(oInstance); 

    // ... 

    // When you try using these instances, you can pull them from 
    // the list and call functions through IMyInterface 
    oList(3).CallInterfaceMember(/* params */); 

不要試圖將對象轉換爲特定的非接口類型 - 創建從字符串實例,因此您不必實際知識真正的類型 - 你只知道他們可能實現什麼接口。

+0

我將如何使用它來創建對象列表? – adamias

+0

@adamias我將添加一個小樣本來顯示它。你能讀/翻譯C#嗎? (我的C#比我的VB.Net :) :) – xxbbcc

+0

退房http://msdn.microsoft.com/en-us/library/d133hta4(v=vs.110).aspx –