创建一个带有Calls计数器的函数

本文关键字:Calls 计数器 函数 一个 创建 | 更新日期: 2023-09-27 18:01:22

问题很简单:如何使调用代码尽可能简单?我的代码有点笨,但我看不出有什么办法。

using System;
namespace ConsoleApplication48
{
class FunctionWithCounter<T, TResult>
{
    private readonly Func<T, TResult> function;
    public int Calls { get; private set; }
    private FunctionWithCounter(Func<T, TResult> function)
    {
        Calls = 0;
        this.function = function;
    }
    public static implicit operator FunctionWithCounter<T, TResult>(Func<T, TResult> func)
    {
        return new FunctionWithCounter<T, TResult>(func);
    }
    public TResult this[T arg]
    {
        get
        {
            Calls++;
            return function(arg);
        }
    }
}
class Program
{
    static void Main()
    {
        FunctionWithCounter<double, double> func = (Func<double, double>)(x => x*x);
        for (int i = 0; i < 5; i++)
        {
            double d = func[i];
        }
        Console.WriteLine(func.Calls);
        Console.ReadKey();
    }
}
}

所以我使用indexer来调用func[x]而不是func(x),并且有一些困难(不能像void-method那样调用)。但我认为这是最简单的。提供吗?

创建一个带有Calls计数器的函数

为了多出一行,我至少会将其恢复到正常的函数语法。还要去掉隐式构造函数,它并没有真正为您节省任何东西,而且没有它,语法看起来更简单。

class FunctionWithCounter<T, TResult>
{
    public readonly Func<T, TResult> Function;
    public int Calls { get; private set; }
    public FunctionWithCounter(Func<T, TResult> function)
    {
        Calls = 0;
        Function = x =>
            {
                Calls++;
                return function(x);
            };
    }        
}
internal class Program
{
    private static void Main(string[] args)
    {
        var callCounter = new FunctionWithCounter<double,double>(x => x * x);
        var func = callCounter.Function;
        for (int i = 0; i < 5; i++)
        {
            double d = func(i);
        }
        Console.WriteLine(callCounter.Calls);
        Console.ReadKey();
    }
}