代表语法代码复制的通用扩展方法

时间:2019-02-03 21:32:46

标签: c# generics syntax extension-methods

我正在创建一些扩展方法,以帮助收集代码中匿名函数的指标。不幸的是,他们倾向于重复一些代码,我不确定如何删除它们。

    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");
        }
    };

其中4个用于操作,4个用于功能,这意味着我的try {}最终{}经常被重复。如何重新编写此代码以防止重复?

还有一种方法可以内联此行的前两行

Action a = () => { Thread.Sleep(100); }; 
a = a.Instrument();
a();

0 个答案:

没有答案