尝试Catch Finally包装器

时间:2014-10-08 00:01:38

标签: c#

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

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.
}

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

2 个答案:

答案 0 :(得分:4)

Impersonation实施IDisposable,然后将UndoImpersonation()移至Dispose()

答案 1 :(得分:4)

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

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

实现:

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