Domanda

I want to do extension method to all method for try-catch. In following You can see code block - but it doesn't work

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("");
        }  
    }
}
È stato utile?

Soluzione

Declare it like that:

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("");
        }  
    }
}

Usage:

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

Or with params:

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

Notice:

This extension method extends any class object and only supports the Action delegate which:

Encapsulates a method that has no parameters and does not return a value.

You can always support more overloads for more delegates signatures.

Altri suggerimenti

Yes you can.

In your example your extension method will be available when you're working with MethodBaseinstances, in other words, when using reflection (the metadata representation of methods and constructors).

On the other hand, if you want that extension method to be always available you should extend the object class.

Nevertheless do not get confused about the difference between extension methods and aspect oriented programming. If what you want is to make a kind of an interceptor to all method calls then i'd suggest you to see what aspect frameworks are available. I'm not used to that kind of programming so i can't really advise you

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top