使用"在中东和QUOT孔;模式 [英] Using "Hole in the Middle" pattern

查看:101
本文介绍了使用"在中东和QUOT孔;模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结果
我对面传来孔在中间的格局,并认为我可以用它来专门去除一些重复的代码,当我尝试基准不同的方法和前后使用相同的代码每个方法。



我是能够得到与下面的代码工作的基础知识。我开始的 StartingMethod ,其主要目标是呼吁 MainMethod1 &安培; MainMethod2 ,但它确实使通过的 PrePostMethod



我现在想知道的是如何传递参数,并得到一个返回值。 。任何帮助将是巨大的。



感谢



中的代码:

 
公共静态类HoleInTheMiddle
{
公共静态无效StartingMethod()
{
Pre​​PostMethod( MainMethod1);
PrePostMethod(MainMethod2);
}

公共静态无效PrePostMethod(动作的someMethod)
{
Debug.Print(预);

的someMethod();

Debug.Print(邮报);
}

公共静态无效MainMethod1()
{
Debug.Print(这是最主要的方法1);
}

公共静态无效MainMethod2()
{
Debug.Print(这是最主要的方法2);
}
}


解决方案

您可以做一个通用的方法和用途一个通用的委托:

 公共静态TResult PrePostMethod< T1,T2,TResult>(Func键< T1,T2,TResult>的someMethod,一个T1,T2 b)
{
Debug.Print(预);

VAR的结果=的someMethod(A,B);

Debug.Print(邮报);

返回结果;
}

您将需要一个单独的通用过载参数每个号码。



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

解决方案

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.

这篇关于使用&QUOT;在中东和QUOT孔;模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆