如何获取C#中正在执行的当前方法的返回类型和返回类型的泛型?

我有这个代码

    [HttpPost("search")]
    public async Task<actionResult<int>> GetEmployees([FromBody] EmployeeSearchDto employeeSearchParameters)
    {

    }

如何获取

actionResult类型和

int类型

我似乎在反射中找不到返回类型属性。

其他信息:

我要解决的问题

我使用的中介器是在运行时确定响应的。

我有这种方法

    public Task<actionResult<ListDto<EmployeeListItemDto>>> GetEmployees([FromBody] EmployeeSearchDto employeeSearchParameters)
    {
        var request = new GetEmployeesQuery()
        {
            EmployeeSearchParameters = employeeSearchParameters
        };

        var response = await _mediator.Send(request).ConfigureAwait(false); //this  returns a response is determined in runtime due to mediatr that contains a property Ienumerable<T> T as employee


        return base.ProcessResponse(response); //this returns and ObjectResult with values from the database
    }

问题在于,当我们替换返回类型

Task<actionResult<ListDto<EmployeeListItemDto>>>

Task<actionResult<int>> 

它仍然运行,并且由于int返回类型,Swagger将0显示为成功响应。

有人问我是否有办法防止这种情况发生,

我想比较一下response.ResponseValues返回IEnumerable的返回类型

actionResult,如果它们在运行时相等。

基本上我们要实现的是类型安全性,我不知道这是不可能的,所以我诉诸反射。

更新 我尝试使用RB的解决方案,但不确定如何使用。

public Task<actionResult<ListDto<EmployeeListItemDto>>> GetEmployees([FromBody] EmployeeSearchDto employeeSearchParameters)
{
    var request = new GetEmployeesQuery()
    {
        EmployeeSearchParameters = employeeSearchParameters
    };

    var response = await _mediator.Send(request).ConfigureAwait(false); //this  returns a response is determined in runtime due to mediatr that contains a property Ienumerable<T> T as employee
GetMethodInfo(GetEmployees); //Im getting cannot be inferred from the usage error.


    return base.ProcessResponse(response); //this returns and ObjectResult with values from the database
}

    public Type GetMethodInfo<T>(Func<T> foo)
    {
        return foo.GetType().GetGenericArguments().Single();
    }

无法从使用错误中推断出我的收获

huanghongwang123 回答:如何获取C#中正在执行的当前方法的返回类型和返回类型的泛型?

为了找到当前正在执行的方法的返回类型,您需要将MethodBase.GetCurrentMethod()的响应强制转换为MethodInfo

var method = MethodBase.GetCurrentMethod();

var returnType = ((MethodInfo)method).ReturnType;

// You can now inspect the return type as a normal Type.

编辑-异步支持

以上代码不适用于async方法。但是,您可以使用另一种方法来获取正确的值:

public async Task<int> Bob()
{
    var returnType = Utilities.GetMethodInfo(Bob);
    // returnType == typeof(Task<Int32>) 

    return 5;
}

public static class Utilities
{
    public static Type GetMethodInfo<T>(Func<T> foo)
    {
        return foo.GetType().GetGenericArguments().Single();
    }
}
本文链接:https://www.f2er.com/2543617.html

大家都在问