我對收到的警告感到有些困惑。以下是相關代碼:
#nullable enable
public partial class FileTable<TItem> : ComponentBase, IDisposable
{
// bunch of class code
public async Task FilterColumn(Func<TItem, IComparable>? itemProperty, string? searchString)
{
ArgumentNullException.ThrowIfNull(ViewItems);
if (itemProperty == null)
return;
if (searchString == null)
searchString = string.Empty;
await Task.Run(() =>
{
foreach (var item in ViewItems)
{
var property = itemProperty(item.Item);
if (property == null)
continue;
item.IsVisible = property.ToString().ToLower().Contains(searchString.ToLower());
}
});
StateHasChanged();
}
}
我收到了警告property.ToString()如您所見,我已經添加了一堆空檢查,但似乎沒有一個可以擺脫警告。據我所知,這是不可能property的null。顯然我錯過了一些東西......那么什么可能會觸發這個警告?
uj5u.com熱心網友回復:
問題是ToString()可以回傳null;這是不好的做法,但是:它可以:
namespace System
{
public class Object
{
// ...
public virtual string? ToString();
// ...
}
}
如果您排除這種情況,錯誤就會消失:
var s = property.ToString() ?? "";
item.IsVisible = s.ToLower().Contains(searchString.ToLower());
另請注意,使用忽略大小寫的比較比強制額外的字串分配更有效:
item.IsVisible = s.Contains(searchString, StringComparison.CurrentCultureIgnoreCase);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/471365.html
