我正在試圖創建兩個泛型方法,其中一個是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