如何简化此代码,但保留现有功能:
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.
}特权代码可以是一行或多行。
发布于 2014-10-08 00:38:22
您可能不知道的IDisposable模式的另一种选择:
Impersonate(() =>
{
//privileged code goes here.
});执行情况:
void Impersonate(Action action)
{
if (i.ImpersonateValidUser())
{
try
{
action();
}
finally
{
i.UndoImpersonation();
}
}
else
{
throw new Exception("Impersonation failed.");
}
}发布于 2014-10-08 00:03:22
让Impersonation实现IDisposable,然后将UndoImpersonation()移动到Dispose()。
https://stackoverflow.com/questions/26247194
复制相似问题