我在 C# 可空背景關系中使用可空參考型別。
我正在服用一個List<string>
,然后將其轉換為一個新List<string?>
的,Select
就像這樣。然后我用 a 過濾掉null
s Where
,但基礎型別仍然是List<string?>
。
strings = strings
.Select(s => method.ThatReturnsNullableString(s))
.Where(s => s is not null)
.ToList();
當我嘗試將其用作List<string>
時,我收到 CS8619 編譯器警告。一個簡單的解決方案是使用! null-forgiving 運算子和警告消失,但我盡量少用它。
另一種解決方案是使用.Cast<string>
,但我認為這會無緣無故地增加運行時開銷。
我是否沒有向編譯器充分證明該集合是 type string
,或者我缺少什么?
uj5u.com熱心網友回復:
.Where(s => s is not null)
將抑制 null-only 專案并保留 typestring?
的專案,因此結果將為 type List<string?>
。
使用.OfType<string>()
,它將跳過空值并強制轉換string?
為字串,相當于.Where(s => s is not null).Cast<string>()
.
strings = strings
.Select(s => method.ThatReturnsNullableString(s))
.OfType<string>()
.ToList(); // List<string>
uj5u.com熱心網友回復:
我認為 Jodrell 有一個好主意,這是一個值得擴展的模式。但我會使用更簡單的 API。
strings = strings
.Select(s => methodThatReturnsNullableString(s))
.SkipNulls()
.ToList();
擴展代碼:
public static IEnumerable<T> SkipNulls<T>(this IEnumerable<T?> source)
{
foreach (var item in source)
{
if (item is not null)
{
yield return item;
}
}
}
uj5u.com熱心網友回復:
我覺得擴展方法方法的一個稍微干凈的版本是這樣的:
public static IEnumerable<T> Denullify<T>(this IEnumerable<T?> source)
{
foreach (var item in source)
{
if (item is T value)
{
yield return value;
}
}
}
這段代碼:
Console.WriteLine(String.Join(", ", new string?[] { "A", null, "B", }));
Console.WriteLine(String.Join(", ", new string?[] { "A", null, "B", }.Denullify()));
...產生:
A, , B
A, B
uj5u.com熱心網友回復:
你可以寫一個擴展,比如這里的作業示例
public static class EnumerableExtensions
{
public static IEnumerable<T> SkipNull<T, Y>(
this IEnumerable<Y> source,
Func<Y, T?> target)
{
foreach(var item in source)
{
var result = target(item);
if (result is not null)
{
yield return result;
}
}
}
}
你可以這樣使用
public class Program
{
public static void Main()
{
var oddStrings = Enumerable
.Range(1, 100)
.SkipNull(Convert);
}
public static string? Convert(int value)
{
if(value % 2 == 0)
{
return null;
}
return value.ToString();
}
}
但是,我可能會使用OfType<string>
,或者如果兩次列舉序列有問題,請撰寫一個標準函式來一次性處理和過濾序列。當然,除非我在重復這種模式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/515631.html
標籤:C#。网林克可为空的
上一篇:創建一個LINQ運算式以在KeyedCollection的底部獲取正確的屬性
下一篇:C#讀取父ID下的特定節點