如何使用try-catch-finally重构代码

SGa*_*att 2 c# refactoring

我必须创建一堆看起来像这样的方法.更改的内容将是方法名称,返回类型和中间标记的行 - 其余的将是相同的.是否有一种干净的方式来重构这个,以便我不重复自己?

private bool CanPerform(WindowsIdentity identity, string applicationName, int operation)
{
    IAzApplication3 application = null;
    IAzClientContext3 context = null;
    try
    {
        application = this.store.OpenApplication(applicationName, null) as IAzApplication3;

        ulong token = (ulong)identity.Token.ToInt64();
        context = application.InitializeClientContextFromToken(token, null) as IAzClientContext3;

        // lines that change go here
    }
    catch (COMException e)
    {
        throw new SecurityException(string.Format("Unable to check operation '{0}'", operation), e);
    }
    finally
    {
        Marshal.FinalReleaseComObject(context);
        Marshal.FinalReleaseComObject(application);
    }
}
Run Code Online (Sandbox Code Playgroud)

我意识到这可能是基本的东西,但我一个人工作,所以没有人问.

Jon*_*eet 6

听起来像委托在这里是合适的,使用通用方法来覆盖返回类型更改:

private T ExecuteWithIdentity<T>(WindowsIdentity identity,
    string applicationName, int operation,
    Func<IAzApplication3, IAzClientContext3, T> action)
{
    IAzApplication3 application = null;
    IAzClientContext3 context = null;
    try
    {
        application = this.store.OpenApplication(applicationName, null) as IAzApplication3;

        ulong token = (ulong)identity.Token.ToInt64();
        context = application.InitializeClientContextFromToken(token, null) as IAzClientContext3;

        return action(application, context);
    }
    catch (COMException e)
    {
        throw new SecurityException(
            string.Format("Unable to check operation '{0}'", operation), e);
    }
    finally
    {
        Marshal.FinalReleaseComObject(context);
        Marshal.FinalReleaseComObject(application);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您将每个检查的代码放在一个单独的方法中,甚至只使用lambda表达式:

bool check = ExecuteWithIdentity(identity, "Foo", 10,
                         (application, context) => context != null);
Run Code Online (Sandbox Code Playgroud)

要么

string check = ExecuteWithIdentity(identity, "Foo", 10, SomeComplexAction);

...
private static string SomeComplexAction(IAzApplication3 application,
                                        IAzClientContext3 context)
{
    // Do complex checks here, returning whether the user is allowed to
    // perform the operation
}
Run Code Online (Sandbox Code Playgroud)

例如,您可能希望更改委托类型 - 目前尚不清楚operation要用于什么.

我也强烈考虑投射而不是使用as.如果应用程序或上下文是从OpenApplication/ InitializeClientContextFromToken作为非空值返回的,这是非正确的类型,您真的想要处理与返回的空值相同吗?