Вопрос

I'm Trying to create a generic delegate like this:

Func<string, string, IEnumerable<MyPOCO>> del  = 
WCFServiceInstance.GetLabs(SessionStateService.Var1,SessionStateService.Var2));

but it seems because GetLabs is within a WCFServiceInstace the Func delegate just thinks I'm passing it an IEnumerable rather than

Func<string, string, IEnumerable<MyPOCO>> 

which is what I'm trying to pass it.

Это было полезно?

Решение

There's something else wrong with your approach. Are the two arguments supposed to be always SessionStateService.Var1 and SessionStateService.Var2? Or will those be the delegate's arguments?

If you want them to be the delegate's parameters:

Func<string, string, IEnumerable<MyPOCO>> del  =
   WCFServiceInstance.GetLabs;

del(SessionStateService.Var1, SessionStateService.Var2);

If you want the method be invoked with those specific values, use a closure instead:

Func<IEnumerable<MyPOCO>> del  =
   () => WCFServiceInstance.GetLabs(SessionStateService.Var1, SessionStateService.Var2);

del();

Bear in mind that if you use a closure, SessionStateService.Var1 and SessionStateService.Var2 will be evaluated when the delegate is called (line 2), not when it is declared (line 1). So, if you pass this second delegate around and call it later, the values of the arguments might have changed.

If you want to prevent that, you can use eager evaluation, as exemplified by @knittl in the comments:

string var1 = SessionStateService.Var1,
       var2 = SessionStateService.Var2;

Func<IEnumerable<MyPOCO>> del = () => WCFServiceInstance.GetLabs(var1, var2);

Другие советы

Func<string, string, IEnumerable<MyPOCO>> del = WCFServiceInstance.GetLabs;

and then use it like:

del(SessionStateService.Var1,SessionStateService.Var2);

I think you want:

Func<string, string, IEnumerable<MyPOCO>> del = WCFServiceInstance.GetLabs;

That is, assuming WCFServiceInstance.GetLabs has the following signature:

IEnumerable<MyPOCO> WCFServiceInstance.GetLabs(string, string)

I think you want a lambda expression to partially apply the function, fixing the first two arguments:

Func<IEnumerable<MyPOCO>> del  =
  () => WCFServiceInstance.GetLabs(
    SessionStateService.Var1,
    SessionStateService.Var2);

Call as del().

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top