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中文網其他相關文章!