c# - 如何从字符串中获取类引用?
问题描述
在 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 - 代码在 C 中没有用户输入就跳到换行符
- python - 如何使用 pytest 捕获日志标准输出输出?
- java - 在简单的键值数据存储中实现键搜索(通过前缀、后缀和正则表达式)
- python-3.x - Python单元测试找不到模块
- react-tsx - “typeof React”类型上不存在属性“FC”
- apache-spark - Spark:Vectorassembler 抛出错误 org.apache.spark.SparkException:作业因阶段失败而中止:
- c# - 下面的表达式在 nodeJS 中的等价物是什么?
- java - zk 边框布局调整大小事件
- scala - 使用scalaj http库时如何提取SSO cookie
- java - 如何使用 Java ProcessBuilder API 运行交互式 bash?