功能C# - 使用或返回Action

Car*_*ngo 3 c# metaprogramming higher-order-functions

浏览网络以便在C#中更好地处理故障,我将通过以下内容实现策略.第一个对我来说很自然,而另一个实现我不确定它的优点是什么?

1)

static void Fault(Action protectedBlock, Action faultHandler)
{ 
    try
    {
        protectedBlock();
    }
    catch
    {
        faultHandler();
        throw;
    }
}

 

static Action Fault(Action protectedBlock, Action faultHandler)
{
    return () =>
    {
        try
        {
            protectedBlock();
        }
        catch
        {
            faultHandler();
            throw;
        }
    };
}

Run Code Online (Sandbox Code Playgroud)
static void Fault(Action protectedBlock, Action faultHandler)
{ 
    try
    {
        protectedBlock();
    }
    catch
    {
        faultHandler();
        throw;
    }
}

2)

static Action Fault(Action protectedBlock, Action faultHandler)
{
    return () =>
    {
        try
        {
            protectedBlock();
        }
        catch
        {
            faultHandler();
            throw;
        }
    };
}

static void Fault(Action protectedBlock, Action faultHandler)
{ 
    try
    {
        protectedBlock();
    }
    catch
    {
        faultHandler();
        throw;
    }
}

2)在C#中开发高阶函数时的首选策略是什么?

而且,我想知道,如果一种方法比另一种更有效.

Sor*_*rax 5

第二个案例就像一个Faultable行动工厂.如果你传递了你想要做的事情protectedBlock的代表,以及当Exception事件发生时该做什么的代表,faultHandler.这些操作作为聚合返回包装在try/catch结构中Action.我对这两种方法的问题是没有Exception实际被捕获,所以谁将要抓住你的投掷没有关于哪个行动的信息.

2之间的执行差异是它们实际执行的时间.第一个将在被叫时执行.每当Action调用返回时,第二个将执行.我不认为效率差异会很大.