试试Catch Finally包装器

本文关键字:包装 Finally Catch 试试 | 更新日期: 2023-09-27 18:25:49

如何简化此代码但保留现有功能:

var i = new Impersonation();
if (i.ImpersonateValidUser())
{
    try
    {
        //privileged code goes here.
    }
    catch (Exception ex)
    {
        throw;
    }
    finally
    {
        i.UndoImpersonation();
    }
}
else
{
    throw new Exception("Impersonation failed.");
}

类似于这样的东西:

using(var i = new Impersonation())
{
    //privileged code goes here.
}

特权代码可以是一行或多行。

试试Catch Finally包装器

您可能不知道IDisposable模式的替代方案:

Impersonate(() =>
{
   //privileged code goes here.
});

实施:

void Impersonate(Action action) 
{
    if (i.ImpersonateValidUser())
    {
        try
        {
            action();
        } 
        finally
        {
            i.UndoImpersonation();
        }
    }
    else 
    { 
        throw new Exception("Impersonation failed."); 
    }
}

使Impersonation实现IDisposable,然后将UndoImpersonation()移动到Dispose()