如何在多种方法中使用try catch?

Apo*_*ore 4 .net c# try-catch

对不起,如果我的问题很愚蠢,但我有这样的代码:

public Object1 Method1(Object2 parameter)
{
    try
    {
        return this.linkToMyServer.Method1(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}

public Object3 Method2(Object4 parameter)
{
    try
    {
        return this.linkToMyServer.Method2(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}

/* ... */

public ObjectXX Method50(ObjectXY parameter)
{
    try
    {
        return this.linkToMyServer.Method50(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

我想你看到的模式.有没有一种很好的方法只有一次尝试catch并在这个try catch中传递泛型方法?

本能地我会使用代表,但代表必须拥有相同的签名吗?

提前致谢.

问候.

Sri*_*vel 9

每当您看到这样的代码时,您都可以应用模板方法模式.

可能是这样的:

private TResult ExecuteWithExceptionHandling<TParam, TResult>(TParam parameter, Func<TParam, TResult> func)
{
    try
    {
        return func(parameter);
    }
    catch (Exception e)
    {
        this.Logger(e);
    }
    return default(TResult);
}

public Object1 Method1(Object2 parameter)
{
    return ExecuteWithExceptionHandling(parameter, linkToMyServer.Method1);
}

public Object3 Method2(Object4 parameter)
{
    return ExecuteWithExceptionHandling(parameter, linkToMyServer.Method2);
}
Run Code Online (Sandbox Code Playgroud)

等等...