我正在试图创建两个泛型方法,其中一个是void,另一个是返回类型。 void方法使用Action
委托,另一个使用Func
委托。对于无效的方法实现是这样的:带委托参数的泛型方法
public static void ExecuteVoid<T>(Action<T> actionToExecute)
{
string endpointUri = ServiceEndpoints.GetServiceEndpoint(typeof(T));
using (ChannelFactory<T> factory = new ChannelFactory<T>(new BasicHttpBinding(), new EndpointAddress(endpointUri)))
{
T proxy = factory.CreateChannel();
actionToExecute(proxy);
}
}
这工作得很好,但我与非void方法有问题:
public static T ExecuteAndReturn<T>(Func<T> delegateToExecute)
{
string endpointUri = ServiceEndpoints.GetServiceEndpoint(typeof(T));
T valueToReturn;
using (ChannelFactory<T> factory = new ChannelFactory<T>(new BasicHttpBinding(), new EndpointAddress(endpointUri)))
{
T proxy = factory.CreateChannel();
valueToReturn = delegateToExecute();
}
return valueToReturn;
}
现在,当我尝试做一个呼叫像这样的方法:
var result = ServiceFactory.ExecuteAndReturn((IMyService x) => x.Foo());
我得到这个编译错误:
The type arguments for method 'ServiceFactory.ExecuteAndReturn<T>(System.Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Foo()
在这种情况下是一个没有参数返回object
的方法。然后我试图通过明确指定类型调用的方法:
var result = ServiceFactory.ExecuteAndReturn<IMyService>(x => x.Foo());
,但现在我得到另一个异常说
Delegate 'IMyService' does not take 1 arguments.
我真的失去了这里。任何帮助表示赞赏。
IMyService的定义是什么? –
@terrybozzio在这种情况下会是什么类型的'x'呢?该类型需要以某种方式指定。 – PoweredByOrange