簡體   English   中英

c#如何獲取當前正在執行的方法的返回類型和返回類型的泛型類型?

[英]How to get the return type and the generic type of the return type of current method being executed in c#?

我有這個代碼

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

    }

怎么獲得

ActionResult 類型和

整型

我似乎無法在反射中找到返回類型屬性。

附加信息:

我試圖解決的問題

我正在使用在運行時確定響應的中介。

我有這個方法

    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 作為成功響應。

有人問我是否有辦法防止這種情況發生,

我想比較返回 IEnumerable 的 response.ResponseValues 的返回類型

和 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();
    }

無法從使用錯誤中推斷出我的情況

為了找到當前正在執行的方法的返回類型,您需要將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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM