首页 > 解决方案 > 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();

标签: c#genericssyntaxextension-methods

解决方案


推荐阅读