开发者

How to create instance by string Array?

开发者 https://www.devze.com 2023-03-14 07:23 出处:网络
I have 15 string value. For example: excel sheet names: Customers, Products etc. these sheet,s names are the same as db Tables also Ef 4.0开发者_Python百科 Entities Name. (Products.cs, Customers.cs)

I have 15 string value. For example: excel sheet names: Customers, Products etc. these sheet,s names are the same as db Tables also Ef 4.0开发者_Python百科 Entities Name. (Products.cs, Customers.cs)


String[] excelSheets = GetExcelSheetNames(String.Format(@"C:\{0}\{1}", UserName, FileUploadForExcel.FileName));
foreach (String excelSheet in excelSheets)
 {
      GetEntity(excelSheet);
 }

protected TModel GetEntity(string ClassNameFromExcelSheetName)
{
   return(TModel)Activator.CreateInstance(ClassNameFromExcelSheetName);
}

above code is a kind of simple foresight. NOT real codes. How to create instance only using string value?


you can create instance of class by class name in string representation using .NET Reflection

Check the following article on reflection: http://www.codeproject.com/KB/dotnet/Reflection.aspx

System.Reflection.Assembly assem = Assembly.Load("");

object thisObj = assem.CreateInstance("Customers");
foreach (PropertyInfo pi in thisObj.GetType().GetProperties)
{
   // List all properties in object 
   ...
}


You probably could use some kind of Factory design pattern (http://en.wikipedia.org/wiki/Abstract_factory_pattern)


You would have to create these instances yourself, perhaps using AutoMapper.

0

精彩评论

暂无评论...
验证码 换一张
取 消