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

编程入门 行业动态 更新时间:2024-10-15 04:25:48
本文介绍了每当在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#中调用某个方法时,是否有通用的方法来调用另一个方法

本文发布于:2023-11-23 18:54:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622521.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   方法来

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!