问题很简单:如何使调用代码尽可能简单?我的代码有点愚蠢,但我看不到。
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();
}
}
}
所以我使用索引器来调用这样的 func[x] 而不是 func(x),并且有一些困难(不能像 void 方法那样调用)。但我认为这是最简单的。有什么优惠吗?