首页 > 解决方案 > 如何从字符串中获取类引用?

问题描述

在 ASP.Net Core 中,我可以获得所有实体的列表,并通过名称找到特定的实体:

var entities = _context.Model.GetEntityTypes();
var entity = (from e in entities where e.Name == $"MyNamespace.Models.{entityname}" select e).FirstOrDefault();
Console.WriteLine(entity.Name);   //example output:  MyNamespace.Models.Car   

所以我可以将实体名称(或模型名称)作为字符串访问,现在需要将其设为 CsvHelper 使用的类类型,因为它需要:

var records = csvReader.GetRecords<SomeClass>().ToList();  //typical use - not my code.

我试图将我的实体转换为类型,如this answer中所述,所以我这样做:

Assembly assem = typeof(MyNamespace.Models.Car).Assembly;
Type myType = Type.GetType(entity.Name);   //entity.Name example: MyNamespace.Models.Car
var records = csvReader.GetRecords<myType>().ToList();

不幸的是,这会导致:

 error CS0118: 'myType' is a variable but is used like a type

我不明白为什么我会收到这个错误,或者如何继续。

标签: c#asp.net-core

解决方案


推荐阅读