繁体   English   中英

每当在C#中调用方法时,是否有一种通用的方法来调用另一个方法

[英]Is there a generic way to call another method whenever a method is called in C#

我有一个像这样的方法:

public Something MyMethod()
{
    Setup();

    Do something useful...

    TearDown();

    return something;
}

Setup和TearDown方法位于基类中。

我遇到的问题是我必须使用Setup()和TearDown()方法调用一遍又一遍地编写这种类型的方法。

编辑:这个方法的棘手部分是“做一些有用的东西......”仅适用于此方法。 这个部分对我创建的每个方法都不同。

另外,我可以将MyMethod2,MyMethod3放在一个类中。 在所有情况下,我想运行设置和拆解

有没有一种优雅的方式来做到这一点,而不必每次都写这个?

也许我是妄想,但是这是一种向方法添加属性并拦截方法调用的方法,所以我可以在调用之前和之后做一些事情?

只需在抽象基类中实现此方法,如下所示:

public Something MyMethod()
{
    Setup();

    DoSomethingUsefull();

    TearDown();

    return something;
}

protected abstract DoSomethingUsefull();

现在,您只需要覆盖继承类中的一个方法 - DoSomethingUsefull()

这是模板方法模式

像这样使用泛型lambdas委托

public SomeThing MyMethod()
{
    return Execute(() =>
    {
        return new SomeThing();
    });
}


public T Execute<T>(Func<T> func)
{
    if (func == null)
        throw new ArgumentNullException("func");

    try
    {
        Setup();

        return func();
    }
    finally
    {
        TearDown();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM