每当在C#中调用某个方法时,是否有通用的方法来调用另一个方法 [英] Is there a generic way to call another method whenever a method is called in C#

查看:97
本文介绍了每当在C#中调用某个方法时,是否有通用的方法来调用另一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的方法:

  public Something MyMethod()
{
设置();

做一些有用的事情...

TearDown();

会返回一些东西;
}

Setup和TearDown方法在基类中。



我遇到的问题是,我必须通过Setup()和TearDown()方法调用来反复编写这种类型的方法。



编辑:此方法的棘手部分是做一些有用的事情...仅特定于此方法。对于我创建的每种方法,这部分都是不同的。



此外,我可以在一个类中包含MyMethod2,MyMethod3。在所有情况下,我都想运行安装程序并进行拆卸



是否有一种优雅的方法而不必每次都编写此代码? / p>

也许我有点妄想,但是这是一种向方法添加属性并拦截方法调用的方法,因此我可以在调用之前和之后进行操作? p>

解决方案

使用通用 lambdas 代表,例如:

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


public T Execute< T>(Func< T> func)
{
if(func == null)
抛出新的ArgumentNullException( func);

试试
{
Setup();

return func();
}
最终
{
TearDown();
}
}


I have a method something like this:

public Something MyMethod()
{
    Setup();

    Do something useful...

    TearDown();

    return something;
}

The Setup and TearDown methods are in the base class.

The problem I'm having is that I have to write this type of method over and over again with the Setup() and TearDown() method calls.

EDIT: The tricky part of this method is that "Do something useful..." is specific to this method only. This part is different for every method I create.

Also, I can have MyMethod2, MyMethod3, in a single class. In all cases, I would like to run the setup and teardown

Is there an elegant way of doing this without having to write this every single time?

Perhaps I'm delusional, but is a way to add an attribute to the method and intercept the method call, so I can do stuff before and after the call?

解决方案

Use generics, lambdas and delegates like so:

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

这篇关于每当在C#中调用某个方法时,是否有通用的方法来调用另一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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