问题很简单:如何使调用代码尽可能简单?我的代码有点愚蠢,但我认为没办法。
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-method那样调用)。但我认为这是最简单的。有什么优惠吗?
答案 0 :(得分:1)
对于1个额外行的价格,我将其恢复到至少正常的函数语法。也摆脱了隐式构造函数,它并没有真正保存任何东西,没有它,语法看起来更简单。
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();
}
}