【问题标题】:Get Result from Invoke Method from Action Delegate C#从动作委托 C# 调用方法获取结果
【发布时间】:2021-04-02 17:02:59
【问题描述】:

有没有办法从通用动作委托中的调用方法中获取结果?

代码执行

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

类方法

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&lt;&gt; 方法中从该方法ExecuteMethod() 获取返回值并将其分配给out 值?这可以实现吗?

【问题讨论】:

    标签: c# delegates inversion-of-control


    【解决方案1】:

    您可以通过不使用Action 来做到这一点。 C# 中的Actions 是返回voiddelegate,即什么都没有。如果您需要委托的返回值,请使用Func,或者如果您需要它专门返回布尔值,请使用Predicate。像这样:

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

    如果您需要内部 action 来获取参数,请使用其他 Func 类之一,例如 this 一个接受 1 个参数并返回 T

    【讨论】:

    • 您好,我尝试了您的解决方案,但没有奏效,它在action?.Invoke() 给我一个错误?,我如何在调用方法中注入我的 IoC?
    • 谢谢你,我现在明白了,我将返回类型从void 更改为TOutputprotected internal TOutput ExecuteService&lt;TAction, TOuput&gt;(Func&lt;TAction, TOutput&gt; action)。你的信息丰富的 cmets 真的帮了我很多。谢谢!
    猜你喜欢
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多