2013-02-27 1 views
-1

질문은 간단합니다 : 코드를 호출하는 데 가능한 단순하게 만드는 방법은 무엇입니까? 내 코드는 약간 바보 같지만 아무 것도 볼 수 없다.호출 카운터로 함수 만들기

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)과 같이 호출 인덱서를 사용하여, 일부 difficultes있다. 그러나 그것은 내가 생각하기에 가장 간단합니다. 어떤 제안?

+0

그렇다면 특정 오류는 무엇이며 어디에서 발생합니까? –

+1

그리고 당신은 정말로 무엇을 성취하려고합니까? 분명하지 않아. –

+0

@JonSkeet 그는 자신의 재산을 호출하는 횟수를 세는 것처럼 보입니다. –

답변

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