假设某人需要为了报告目的而调用方法调用。出于维护原因,将时间代码放在函数内部是不可行的。
因此,通过使用该Func
调用一个可以做时间的操作,不干扰:
static void Time<T>(Func<T> work)
{
var sw = Stopwatch.StartNew();
var result = work();
Console.WriteLine(sw.Elapsed + ": " + result);
}
然后用我们的函数调用它来进行定时
Time(() => { return "Jabberwocky"; });
结果:
00:00:00.0000926: Jabberwocky
他再是使用相同的时间基序时间正则表达式VS string.split
var strData = "The rain in Spain";
Time((str) => { return Regex.Split(str, @"\s"); }, strData);
Time((str) => { return str.Split(); }, strData);
这里的示例性使用的Funct<T,TResult>
是设置
static void Time<T,S>(Func<T,S> work, T strToSplit)
{
var sw = Stopwatch.StartNew();
var result = work(strToSplit);
sw.Stop();
var joined = string.Join(", ", result as string[]);
Console.WriteLine("{0} : {1}", sw.Elapsed, joined);
}
而且结果
00:00:00.0000232 : The, rain, in, Spain
00:00:00.0000021 : The, rain, in, Spain
更新2017年的答案。这不是Func
,而是其不归属的兄弟Action
;我发现我做我的班记录的基本形式,我使用依赖注入从消费者像这样:
Action<string> ReportIt { get; set; }
public void ReportStatus(Action<string> statusReporter)
{
ReportIt = statusReporter;
}
的想法是,状态报告是可选的,所以在我检查代码后看它是否是vialble如果是的话,我给状态:
ReportIt?.Invoke("Running - Connection initiated");
类的消费者称之为如
piperInstance.ReportStatus(Console.WriteLine);
whic h后也可表现为
piperInstance.ReportStatus((str) => { Console.WriteLine(str); });
查看IEnumerable''Where'()''和其他extesnion方法的linq源代码,你会明白它在哪里有用以及如何使用 –
可能的重复[你如何使用Func < >和Action <>在设计应用程序时?](http://stackoverflow.com/questions/1537404/how-do-you-use-func-and-action-when-designing-applications) –
我结合字典和func( 'Dictionary>'在读取非托管资源时对特定键执行一些操作。 –