C# 泛型类型推断限制:接口约束的情况
C# 的泛型方法提供了跨不同类型的适应性数据处理。 然而,编译器的自动类型推断并不总是成功。 在处理泛型方法中的接口约束时,这种限制变得明显。
考虑这个例子:
<code class="language-csharp">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(); // Compilation Error: Type inference failed p.Process(query); // Explicit type arguments required for successful compilation p.Process<SomeQuery, string>(query); } }</code>
编译器无法在第一个 TQuery
调用中推断 TResult
和 p.Process(query)
。 原因是 C# 的类型推断机制依赖于所提供参数的 types。 虽然 query
属于 SomeQuery
类型,但仅此并不能完全定义 TQuery
和 TResult
。
约束where TQuery : IQuery<TResult>
允许多个IQuery
实现,但编译器无法从参数类型推断出精确的实现。 因此,需要显式类型参数 (<SomeQuery, string>
) 来解析泛型类型。
正如 Eric Lippert 所解释的(https://www.php.cn/link/4a3cffe005397d4cffdee044f1c8d30e),约束不是方法签名的一部分,因此不用于类型推理。 推理仅基于形式参数类型,最重要的是,它排除了约束。
以上是为什么 C# 无法推断具有接口约束的方法中的泛型类型参数?的详细内容。更多信息请关注PHP中文网其他相关文章!