C#可能为空的引用解除引用

3

我对收到的警告有些困惑。以下是相关代码:

#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()处收到警告。如您所见,我已添加了许多null检查,但似乎没有一个能消除该警告。就我所知,此时property不可能是null。显然,我错过了什么...那么是什么触发了这个警告?


3
抱歉,我可能没有理解您的请求。您希望我翻译这个句子吗?如果是的话,我会将其翻译成中文:"这是否意味着在调用ToString()方法时有可能返回null值而感到抱怨?" - Martin Costello
property 的数据类型是什么,而 itemProperty() 的返回类型是什么? - gunr2171
@gunr2171 问题已经解决,但为了澄清:整个类是自定义“表格”组件的代码后端,应该接受任何类型的集合并添加额外的功能,如排序和过滤。我使用itemProperty()来搜索相应列的属性。 - Roland Deschain
1个回答

6
问题在于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);

好的,就是这样了。我会尽快标记答案。 - Roland Deschain
1
@RolandDeschain 请注意编辑(最后一行) - Marc Gravell
顺便说一句,谢谢你提醒忽略大小写的问题 :) - Roland Deschain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接