[英]Generic methods with delegate parameters
我正在尝试创建两个通用方法,其中一个是void,另一个具有返回类型。 void方法接受一个Action
委托,另一个接受Func
委托。 void方法的实现如下所示:
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);
}
}
这工作正常,但我在使用非无效方法时遇到问题:
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.
我真的在这里迷路了。 任何帮助表示赞赏。
您可能会将返回类型与代理类型混淆。 如果将参数指定为Func<T>
,则T
需要是函数的返回类型,而不是代理类型。 但是,您还需要指定代理类型,以获取正确的服务端点和通道工厂。 因此,您实际上需要两个类型参数:一个用于代理,一个用于返回类型。 我还假设函数委托需要使用初始化的代理作为参数; 否则,这种包装方法将毫无意义。
public static TResult ExecuteAndReturn<TProxy, TResult>(
Func<TProxy, TResult> delegateToExecute)
{
string endpointUri = ServiceEndpoints.GetServiceEndpoint(typeof(TProxy));
TResult valueToReturn;
using (ChannelFactory<TProxy> factory = new ChannelFactory<TProxy>(new BasicHttpBinding(), new EndpointAddress(endpointUri)))
{
TProxy proxy = factory.CreateChannel();
valueToReturn = delegateToExecute(proxy);
}
return valueToReturn;
}
编辑 :出现编译器错误是因为(IMyService x) => x.Foo()
与Func<T>
委托不兼容。 在编写匿名函数时,推断的类型是匿名函数本身的类型,而不是它碰巧调用的方法。 在这种情况下,匿名函数接受IMyService
类型的单个参数,并返回object
(即Foo
的返回类型)。 因此,此匿名方法的正确委托将是Func<IMyService, object>
。
您已将参数定义为func<x>
即没有参数的委托,然后将其称为Func<x,y>
,即将其接受1个参数IMyService的委托,因此错误“ Delegate'IMyService'不接受1个参数“
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.