我们可以为所有方法编写扩展方法吗?

时间:2014-01-20 12:13:49

标签: c# exception-handling extension-methods

我想对try-catch的所有方法做扩展方法。在下面您可以看到代码块 - 但它不起作用

public static class TryCatchExtention
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public static void WithTryCatch(this MethodBase method) 
    {
        try
        {
            //method.Invoke();
        }
        catch (Exception ex)
        {
            log.Error("Error : {0} " + ex.Message);
            throw new ApplicationException("");
        }  
    }
}

2 个答案:

答案 0 :(得分:3)

声明如下:

public static class TryCatchExtention
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public static void WithTryCatch(this object theClass, Action theMethod) 
    {
        try
        {
            theMethod.Invoke();
        }
        catch (Exception ex)
        {
            log.Error("Error : {0} " + ex.Message);
            throw new ApplicationException("");
        }  
    }
}

<强>用法:

var yourClass = new YourClass();
//Pass here the method to be wrapped with a `try-catch` block
yourClass.WithTryCatch(this.YourMethod);}

或者使用params:

yourClass.WithTryCatch(()=> this.YourMethod(params...));}

<强>注意:

此扩展方法扩展了任何class对象,仅支持Action委托:

  

封装没有参数但不返回的方法   值。

您可以随时为更多代理签名支持更多重载。

答案 1 :(得分:1)

是的,你可以。

在您的示例中,当您使用MethodBase实例时,换句话说,使用反射(方法和构造函数的元数据表示)时,您的扩展方法将可用。

另一方面,如果您希望该扩展方法始终可用,则应扩展object类。

尽管如此,不要对扩展方法和面向方面编程之间的区别感到困惑。如果您想要的是为所有方法调用创建一种拦截器,那么我建议您查看哪些方面框架可用。 我不习惯那种编程,所以我无法真正建议你

相关问题