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

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - Using "Hole in the Middle" pattern


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...