对于泛型方法,我获得了很多实用的乐趣(旨在获得乐趣).在大多数情况下,C#类型推断足够智能,可以找出它必须在我的泛型方法上使用什么泛型参数,但是现在我得到了一个设计,其中C#编译器没有成功,而我相信它本可以成功地找到正确的类型.
有没有人能告诉我,编译器在这种情况下是不是有点笨,或者它为什么不能推断出我的泛型参数,有没有一个非常明确的原因?
以下是代码:
类和接口定义:
interface IQuery<TResult> { }
interface IQueryProcessor
{
TResult Process<TQuery, TResult>(TQuery query)
where TQuery : IQuery<TResult>;
}
class SomeQuery : IQuery<string>
{
}
一些未编译的代码:
class Test
{
void Test(IQueryProcessor p)
{
var query = new SomeQuery();
// Does not compile :-(
p.Process(query);
// Must explicitly write all arguments
p.Process<SomeQuery, string>(query);
}
}
这是为什么呢?我错过了什么吗?
以下是编译器错误消息(它不会给我们留下太多想象空间):
方法IQueryProcessor的类型参数.过程<;查里,
我认为C#能够推断出这一点的原因是:
- 我提供了一个实现
IQuery<TResult>
的对象. - 类型实现的只有
IQuery<TResult>
个版本是IQuery<string>
,因此TResult必须是string
. - 有了这些信息,编译器就有了TResult和TQuery.