2013-07-03 2 views
0

아래에는 매개 변수가없는 매개 변수가있는 작업을 실행하는 데 도움이되는 몇 가지 방법이 있으며 작동합니다. 내가 없애 싶어 문제가 그러나 는 문제는 내가Dynmic 매개 변수 및 매개 변수없는 작업 실행

Execute<Action<Myclass>, Myclass>(ActionWithParameter); 

를 호출 할 때 나는 MyClass 2 번 통과하고 있다는 점이다. 내 ActionWithParameter 작업에 필요한 매개 변수를 처음 정의하고 두 번째로 내 Execute<TAction, TType> 메서드에서 예상하는 매개 변수 유형을 정의합니다.

그럼 제 질문은 : 제 2 일반용 TType을 없애고 어떻게 든 제네릭 TAction에서 가져 오는 방법이 있습니까?

TAction<TType>일까요?

class Program 
    { 
     static void Main(string[] args) 
     { 
      Execute<Action>(ActionWithoutParameter); 
      Execute<Action<Myclass>, Myclass>(ActionWithParameter); 

      Console.ReadLine(); 
     } 

     private static void ActionWithoutParameter() 
     { 
      Console.WriteLine("executed no parameter"); 
     } 

     private static void ActionWithParameter(Myclass number) 
     { 
      Console.WriteLine("executed no parameter " + number.ID); 
     } 

     private static void Execute<TAction>(TAction OnSuccess) 
     { 
      Execute<TAction, Myclass>(OnSuccess); 
     } 
     private static void Execute<TAction, TType>(TAction OnSuccess) 
     { 
      if (OnSuccess is Action) 
      { 
       Action method = OnSuccess as Action; 
       method(); 
      } 
      else if (OnSuccess is Action<TType>) 
      { 
       Myclass myclass = new Myclass() { ID = 123 }; 
       TType result = (TType)(object)myclass; 
       Action<TType> method = OnSuccess as Action<TType>; 
       method(result); 
      } 
     } 
+0

태그를 언어 태그로 바꾸기를 선택하는 것이 좋습니다. –

+0

태그에 C#을 추가했습니다. 제안 해 주셔서 감사합니다. – Daniel

답변

0

어쩌면 트릭 할 것입니다 방법의 제네릭이 아닌 및 일반 버전을 사용 :

public static void Execute<TType>(Action<TType> OnSuccess) 
     where TType : Myclass // gets rid of unnecessary type-casts - or you just use Action<Myclass> directly - without the generic parameter... 
    { 
     // throw an exception or just do nothing - it's up to you... 
     if (OnSuccess == null) 
      throw new ArgumentNullException("OnSuccess"); // return; 

     TType result = new Myclass() { ID = 123 }; 
     OnSuccess(result); 
    } 

    public static void Execute(Action OnSuccess) 
    { 
     if (OnSuccess == null) 
      throw new ArgumentNullException(); // return; 

     OnSuccess();    
    } 

(그러나 나는 결과 생성 + 액션 실행의 목적에 대해 너무 잘 모르겠어요를 - 단순히 비 일반적인 Execute(Action) 버전 만 사용하면 가능합니다.)