從 .NET 10 開始,兩個延伸模組方法和System.Linq.Queryable.MinBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TSource>)接受 an IComparer<TSource> 的延伸模組方法System.Linq.Queryable.MaxBy<TSource,TKey>(IQueryable<TSource>, Expression<Func<TSource,TKey>>, IComparer<TSource>)已過時。 請改用新新增的接受IComparer<TKey>
在程式碼中呼叫這些舊的擴充方法會在編譯階段產生警告SYSLIB0061,並且通常會在執行階段產生IndexOutOfRangeException
過時原因
原始MaxBy和MinBy接受IComparer<T>? comparer運算式參數使用類型參數的IComparer<T>? comparer泛型類型TSource錯誤地實作。 這是不正確的,因為傳遞給 Comparer<T>.Compare(T, T) 方法的值是由表達式參數選擇 Expression<Func<TSource, TKey>> keySelector 的,因此提取的值是泛型類型 TKey。
備註
這以前只有在 和 TKey 實際上是相同的建構類型時TSource才有效。 如果類型不同,則執行階段 IndexOutOfRangeException:索引超出陣列的界限。 會擲回,因為找不到所需的擴充方法 IQueryable<TSource> source (例如,在 MaxBy中)。
因應措施
使用接受參數的新IComparer<TKey>? comparer新增 MaxBy or MinBy 方法。 這些不會擲回例外狀況。
例如:
// This worked correctly since TKey and TSource are both int.
Enumerable.Range(1, 10)
.AsQueryable()
.MaxBy(key => (0 - key), Comparer<int>.Default);
// This would throw since TKey is string but TSource is int
// and will trigger the obsoletion warning now and would
// throw an exeception at runtime.
Enumerable.Range(1, 10)
.AsQueryable()
.MaxBy(key => key.ToString(), Comparer<int>.Default);
// This previously would not compile before to the addition of
// the new methods since TKey is string and TSource is int.
// It will now compile and execute correctly.
Enumerable.Range(1, 10)
.AsQueryable()
.MaxBy(key => key.ToString(), Comparer<string>.Default);
隱藏警告
如果您必須使用過時的 API,您可以在程式碼或專案檔中隱藏警告。
若要僅抑制單一違規,請將預處理器指示詞新增至來源檔案以停用,然後重新啟用警告。
// Disable the warning.
#pragma warning disable SYSLIB0061
// Code that uses obsolete API.
// ...
// Re-enable the warning.
#pragma warning restore SYSLIB0061
若要隱藏 SYSLIB0061 專案中的所有警告,請將屬性新增至 <NoWarn> 專案檔。
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
...
<NoWarn>$(NoWarn);SYSLIB0061</NoWarn>
</PropertyGroup>
</Project>
如需詳細資訊,請參閱 隱藏警告。