2017-03-03 45 views
0

我有一個看起來像這樣識別一個FUNC傳遞的類型

public interface IMyService 
{ 
    T ServiceProxy<T>(Func<IService, T> request) where T : Response; 
} 

一個接口,它的用法是這樣的:

_mysvc.ServiceProxy((p) => p.Execute(new ActivateAccountRequest())); 
_mysvc.ServiceProxy((p) => p.Execute(new DeleteAccountRequest())); 

即各種不同的請求類型發送用於ServiceProxy方法包裹在Func中。所有請求子類相同的基類

我需要爲測試目的創建此接口的假實現。我想基於什麼類型的請求傳遞給方法

但我不能工作,如何識別傳入的請求的類型用於ServiceProxy方法

例如,如果做不同的事這是一個ActivateAccountRequest我想做一件事,如果是DeleteAccountRequest我想做另一個

有什麼想法?

+1

如果您想基於參數類型做不同的事情,請使用重載而不是泛​​型。 – Lee

+1

'typeof(T)'起作用。 *爲什麼*你想這樣做?使用泛型的一點是你不需要知道具體的類型。如果你這樣做,你可能需要使用重載或某種Visitor實現(它也使用重載)。 –

+1

如果你正在測試你確切地知道你的測試的輸入是什麼,因此對於任何給定的測試,類型是什麼......你能解釋一下你的測試是什麼以及你想要做什麼,在類型? – Chris

回答

1

更改你的界面:

T ServiceProxy<T>(Expression<Func<IService, T>> request) where T : Response; 

現在使用這個擴展的方法來獲取函數參數:

public static IEnumerable<object> GetFunctionParameters<TInput, TOutput>(this Expression<Func<TInput, TOutput>> expression) 
     { 
      var call = expression.Body as MethodCallExpression; 
      if (call == null) 
       throw new ArgumentException("Not a method call"); 

      foreach (Expression argument in call.Arguments) 
      { 
       LambdaExpression lambda = Expression.Lambda(argument, expression.Parameters); 
       Delegate d = lambda.Compile(); 
       yield return d.DynamicInvoke(new object[1]); 
      } 
     } 

,然後簡單地調用request.GetFunctionParameters().First().GetType();

+0

抱歉 - 更改接口不是一個選項我有 – ChrisCa

-1

也許您正在尋找這樣的:

class MyService : IMyService 
{ 
    public T ServiceProxy<T>(Func<IService, T> request) where T : Response 
    { 
     var type = typeof(T); 
     if(type == typeof(ActivateAccountRequest)) 
     { 
      //do your stuff 
     } 
     if(type == typeof(DeleteAccountRequest)) {/*other stuff*/ } 
    } 
} 
+1

此函數將返回p.Execute(new ActivateAccountRequest())調用的結果類型 – MistyK