我需要一种创建对象列表的方法,其中对象来自字符串
例如,我想将下面的内容转换为对象列表
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
答案 0 :(得分:1)
您可以使用Activator.CreateInstance
根据字符串程序集名称/类型名称创建对象。 (该方法也有许多其他重载。)
调用返回Object
,因此您必须将其强制转换为已知类型(例如,接口类型)。据我所知(我不是VB.Net专家),没有办法用字符串类型名称定义变量,所以你需要
Object
- s列表中(这样可行,但您不会以这种方式真正拥有可用对象)。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 */ );
不要尝试将对象转换为特定的非接口类型 - 您可以从字符串创建实例,这样您就无法了解实际类型 - 您只知道它们的接口是什么>可能实施。