我需要一种方法来创建对象列表,其中对象来自字符串。
例如,我希望将下面的内容转换为对象列表
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对象列表。
这是通过下拉区域上传文件以及表名、对象类名和映射类名来实现的。这现在允许我使用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发布于 2015-01-08 19:46:07
可以使用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 */ );不要试图将对象转换为特定的非接口类型--您是从字符串创建实例的,因此您不了解实际类型--您只知道它们可能实现哪些接口。
https://stackoverflow.com/questions/27848275
复制相似问题