我有一个类似这样的方法:
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#中调用某个方法时,是否有通用的方法来调用另一个方法
发布评论