我有一个测试应用程序,有一个类 TestSeq 和一个方法 Go(),它由这样的 block 组成:
_writer.WriteLine("Doing foo action...");
var stopwatch = Stopwatch.StartNew();
// foo - some work here
stopwatch.Stop();
_writer.WriteDone("Results of foo action.", stopwatch.Elapsed);
在“一些工作”中,我对 WCF 客户端进行了不同的调用(CRUD 操作、过滤器等)。
所以,很多代码重复,显然应该在这里进行一些重构。我考虑创建一个类 TestAction,但我不知道将“一些工作”部分放入其中的最佳方法是什么。
在我看来,这是一个很简单的问题,但我就是不知道应该搜索什么关键字。因此,我很高兴看到仅包含关键字(模式名称或其他内容)或链接的答案。
最佳答案
我敢肯定还有更多,但在我的脑海中,您可能可以通过两种方式编写此样板代码。
方法一:使用using语法将感兴趣的代码包裹起来
class MeasuredOperation : IDisposable
{
Stopwatch stopwatch;
string message;
public MeasuredOperation(string message)
{
Console.WriteLine("Started {0}", message);
stopwatch = Stopwatch.StartNew();
this.message = message;
}
public void Dispose()
{
stopwatch.Stop();
Console.WriteLine("Results of {0} Elapsed {1}", this.message, this.stopwatch.Elapsed);
}
}
static void Main(string[] args)
{
using (new MeasuredOperation("foo action"))
{
// Do your action
}
}
方法 2:创建一个新函数并将您的代码块作为委托(delegate)传递
static void MeasuredAction(string message, Action action)
{
Console.WriteLine("Started {0}", message);
var stopwatch = Stopwatch.StartNew();
action();
stopwatch.Stop();
Console.WriteLine("Results of {0} Elapsed {1}", message, stopwatch.Elapsed);
}
static void Main(string[] args)
{
MeasureAction(delegate()
{
// do work
});
}
关于c# - 如何重构测试应用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10266012/