c# - 如何将泛型类型传递给泛型方法
问题描述
这是我需要做的:
接收作为字符串的实体名称,然后返回该特定表的数据库内容。
1- 从获取请求中接收实体名称
[HttpGet]
[Route("/api/[controller]/GetByEntity")]
public IActionResult GetAll(string entity)
{
try
{
Type type = Type.GetType(entity);
return Ok(Unit.BasicRegisterRepository.GetByEntity<type>());
}
catch(Exception e)
{
return BadRequest(e);
}
}
2- 返回数据
public List<T> GetByEntity<T>() where T : class
{
var query = this.DbContext.Set<T>();
var result = query.ToList();
return result;
}
问题:将type
as 参数传递给GetByEntity<type>
函数时,出现以下错误:
type is a variable but used as a type
我究竟做错了什么?
谢谢!
解决方案
我找到了解决方案!我需要使用反射来使其工作。
这是更新的代码:
[HttpGet]
[Route("/api/[controller]/GetByEntity")]
public IActionResult GetAll(string entity)
{
try
{
Type type = Type.GetType(entity);
var getByEntityMethod = Unit.BasicRegisterRepository.GetType().GetMethod("GetByEntity").MakeGenericMethod(type);
return Ok(getByEntityMethod.Invoke(Unit.BasicRegisterRepository, new Object[] { }));
}
catch(Exception e)
{
return BadRequest(e);
}
}
推荐阅读
- react-native - React-navigation 抽屉在渲染项目屏幕后立即将我路由回上一个屏幕
- javascript - 如何在不将用户重定向到该 URL 页面的情况下发送 GET 值?
- python-3.x - 代码中使用的空字典是什么?
- recursion - 文本 WebAssembly 中的递归斐波那契
- php - 值匹配时组合 2 个数组
- ios - 如何在没有应用调用堆栈的情况下解决 iOS 崩溃?
- android - 在 Intellij / Android Studio 中查找所有说“需要 API 级别”的问题
- javascript - 用纯 javascript 节流
- jenkins - 如何使用 Jenkins 的 Rhapsody 生成代码 - 面对许可证问题
- jquery - 与 LaravelMix 一起使用时缺少 TinyMCE 主题文件