【发布时间】:2021-11-14 17:10:59
【问题描述】:
在我的项目中,我遇到了 get 方法的返回类型为 OkObjectResult
的情况public IActionResult GetById(int Id)
{
...
return Ok(returnObj);
}
我必须在另一个地方调用它并将其转换为该方法的模型类型。
public IActionResult AnotherMethod(int Id)
{
...
var data = (Model)GetById(Id); //casting
return Ok(returnObj);
}
我使用了 casting,但它在输出中显示错误 无法将类型“Microsoft.AspNetCore.Mvc.OkObjectResult”的对象转换为类型“Entities.Model” .
是否可以以某种方式将其转换为模型类型?
【问题讨论】:
-
为什么不把 GetById() 的内容(减去 return Ok())放到一个函数中,然后从两者中调用呢?
-
@juunas 实际上,我想重用 GetById(int Id) 而不是创建另一个函数来避免复杂性并一次又一次地编写相同的东西。有没有办法转换它?
-
你能告诉我你想在AnotherMethod中返回哪个结果,你想得到OK结果的模型并在另一个方法中使用它吗? ?
-
@BrandoZhang 我需要在 GetById(int Id) 中使用过的 Model 类型,我将在 AnotherMethod(int Id) 方法的一个地方使用该 Model 类型。 AnotherMethod(int Id) 也将返回 OkObjectResult
标签: asp.net-core casting type-conversion asp.net-core-webapi