【发布时间】:2026-02-23 14:55:01
【问题描述】:
我正在尝试创建两个泛型方法,其中一个是 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);
}
}
这很好用,但我在使用非 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的类型是什么?需要以某种方式指定类型。