簡體   English   中英

從動作委托 C# 調用方法獲取結果

[英]Get Result from Invoke Method from Action Delegate C#

有沒有辦法從通用動作委托中的調用方法獲取結果?

代碼執行

public string TestRun()
{
   ExecuteService<SomeClass>(e => e.ExecuteMethod(), out var result);
   return result; // return the value;
}

Class 方法

public class SomeClass
{
    public string ExecuteMethod()
    {
        return "Hello!?";
    }
}

執行通用動作委托的方法

protected internal void ExecuteService<TAction>(Action<TAction> action, out Response response) where TAction : new()
{
    action?.Invoke(new TAction()); // invoke
    response = action?.something() // problem... how to get the value from this point forward
}

如何在動作委托ExecuteService<>方法中從此方法ExecuteMethod()獲取返回值並將其分配給out值? 這是可以實現的嗎?

您可以通過不使用Action來做到這一點。 C# 中的Action是一個返回void委托,即什么也沒有。 如果您需要委托的返回值,請使用Func或者如果您需要它專門返回 boolean 使用Predicate 像這樣:

protected internal void ExecuteService<TAction>(Func<TAction> action, out Response response)
{
    response = action?.Invoke();
}

如果您需要內部action來獲取參數,請使用其他Func類之一,例如這個接受 1 個參數並返回T

暫無
暫無

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

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