Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories


I just came across the "Hole in the Middle" pattern and think that I can use it to remove some repetitive code specially when I try to benchmark different methods and use the same code before and after each method.

I was able to get the basics working with the code below. I start with StartingMethod, whose main goal is to call MainMethod1 & MainMethod2, but it does so through PrePostMethod.

What I want to know now is how to pass parameters and get a return value. Any help will be great.

Thanks.

The code:

public static class HoleInTheMiddle
    {
        public static void StartingMethod()
        {
            PrePostMethod(MainMethod1);
            PrePostMethod(MainMethod2);
        }

        public static void PrePostMethod(Action someMethod)
        {
            Debug.Print("Pre");

            someMethod();

            Debug.Print("Post");
        }

        public static void MainMethod1()
        {
            Debug.Print("This is the Main Method 1");
        }

        public static void MainMethod2()
        {
            Debug.Print("This is the Main Method 2");
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

You can make a generic method and use a generic delegate:

public static TResult PrePostMethod<T1, T2, TResult>(Func<T1, T2, TResult> someMethod, T1 a, T2 b)
{
    Debug.Print("Pre");

    var result = someMethod(a, b);

    Debug.Print("Post");

    return result;
}

You'll need a separate generic overload for each number of parameters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...