繁体   English   中英

C# 取消引用可能的 null 引用

[英]C# Dereference of a possibly null reference

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

#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 显然我遗漏了一些东西……那么是什么触发了这个警告?

问题是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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM