比方說,我有一個服務接口,看起來像這樣:爲什麼在這段代碼中不能使用類型推斷?
public interface IFooService
{
FooResponse Foo(FooRequest request);
}
我想呼籲喜歡這些服務的方法時,以滿足一些橫切關注點;例如,我想要統一的請求記錄,性能記錄和錯誤處理。我的做法是有一個共同的基礎「庫」與Invoke
方法,它調用的方法和它周圍做其他事情的護理類我的基類看起來是這樣的:。
public class RepositoryBase<TService>
{
private Func<TService> serviceFactory;
public RepositoryBase(Func<TService> serviceFactory)
{
this.serviceFactory = serviceFactory;
}
public TResponse Invoke<TRequest, TResponse>(
Func<TService, Func<TRequest, TResponse>> methodExpr,
TRequest request)
{
// Do cross-cutting code
var service = this.serviceFactory();
var method = methodExpr(service);
return method(request);
}
}
這正常不過,我的整個使代碼更清潔的目標是通過類型推斷工作不正常的事實挫敗例如,如果我寫這樣一個方法:
public class FooRepository : BaseRepository<IFooService>
{
// ...
public BarResponse CallFoo(...)
{
FooRequest request = ...;
var response = this.Invoke(svc => svc.Foo, request);
return response;
}
}
我得到這個編譯錯誤:
The type arguments for method ... cannot be inferred from the usage. Try specifying the type arguments explicitly.
很顯然,我可以改變我的電話來解決它:
var response = this.Invoke<FooRequest, FooResponse>(svc => svc.Foo, request);
,但我想避免這種情況。有沒有辦法重寫代碼,以便我可以利用類型推斷?
編輯:
我還要提到的是較早的方法是使用一個擴展方法;此工作的類型推斷:
public static class ServiceExtensions
{
public static TResponse Invoke<TRequest, TResponse>(
this IService service,
Func<TRequest, TResponse> method,
TRequest request)
{
// Do other stuff
return method(request);
}
}
public class Foo
{
public void SomeMethod()
{
IService svc = ...;
FooRequest request = ...;
svc.Invoke(svc.Foo, request);
}
}
我明白了;這就說得通了。 – Jacob 2012-04-19 21:28:34