簡體   English   中英

為什么我不能將可空元組用於可空泛型參數

[英]Why can't I use a nullable tuple for a nullable generic parameter

所以我想知道你是否可以創建一個擴展方法,將.Where().Select()的功能結合起來,用於過濾掉列表的 null 值並保持類型與可空引用類型一致的特殊情況。 這意味着如果我得到一個string?[]它將過濾掉所有null值並返回一個沒有可為空字符串的IEnumerable<string>

但是,當我嘗試過濾出如下所示的可空元組時,我收到編譯器錯誤,即預期不可空元組類型。 為什么此解決方案適用於所有常規類型但不適用於元組,以及如何更改我的擴展方法以也適用於元組。

擴展方法:

public static IEnumerable<TResult> SelectNotNull<TSource, TResult>
(this IEnumerable<TSource> enumerable, Func<TSource, TResult?> selector)
{
    foreach (var item in enumerable)
        if (selector(item) is { } result)
            yield return result;
}

產生編譯器錯誤的示例代碼:

(string?, int)[] arr = Array.Empty<(string?, int)>();

static (string, int)? Selector((string?, int) x)
{
    return x.Item1 != null ? x : null;
}

arr.SelectNotNull<(string?, int), (string, int)>(Selector);

沒有約束,你的TResult? 被解釋為引用類型可空性注釋(如果未啟用引用類型可空性,您應該看到 CS8632 警告,或者如果使用早期的 C# 編譯器版本,則會看到硬錯誤) - 可空性注釋只是建議性 他們不會改變任何艱難的行為。 使用值類型獲得您似乎想要的行為,您可以添加:

public static IEnumerable<TResult> SelectNotNull<TSource, TResult>
(this IEnumerable<TSource> enumerable, Func<TSource, TResult?> selector)
    where TResult : struct // <== add constraint

但是,這根本不適用於引用類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM