假設某人需要爲了報告目的而調用方法調用。出於維護原因,將時間代碼放在函數內部是不可行的。
因此,通過使用該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>'在讀取非託管資源時對特定鍵執行一些操作。 –