c# - Generic extension methods for delegates syntax code duplication
问题描述
I'm creating some extension methods to help gather metrics on anonymous functions in my code. unfortunately, they tend to have some code duplication and I'm unsure how to remove it.
public static Action Instrument(this Action a, [CallerMemberName] string caller = null)
=> () =>
{
var sw = Stopwatch.StartNew();
try
{
a();
}
finally
{
Trace.WriteLine($"{caller} : {sw.ElapsedMilliseconds} ms");
}
};
public static Action<T> Instrument<T>(this Action<T> a, [CallerMemberName] string caller = null)
=> (t) =>
{
var sw = Stopwatch.StartNew();
try
{
a(t);
}
finally
{
Trace.WriteLine($"{caller} : {sw.ElapsedMilliseconds} ms");
}
};
having 4 of these for actions and 4 for functions means that my try{ } finally{ } gets duplicated way too often. How do I re-write this to prevent the duplication?
Also is there a way to inline the first 2 lines of this
Action a = () => { Thread.Sleep(100); };
a = a.Instrument();
a();
解决方案
推荐阅读
- z3 - z3 从 int 到 float 的转换,反之亦然,适用于任何表达式
- python - Python Scipy:“TypeError:fsolve:'func'参数的输入和输出形状不匹配”
- javascript - 如何更换 2 | 凭什么?
- python-3.x - Google App Engine Cron Job 目标未使用正确的 url
- r - 绘制岭回归 MSE 的交叉验证
- linux - 我如何计算具有特定八进制代码的文件数而不显示在外壳中
- powershell - Powershell字符串到csv
- javascript - 将鼠标悬停在文本上时弹出图像并跟随鼠标->向下滚动时出现问题
- c++ - QTimer 单发,在捕获中传递 lambda 异常
- flutter - 在同步调用中返回 Future 的结果