【问题标题】:Why is a Warning about a nullable type issued, even though there can be no null value?为什么发出关于可空类型的警告,即使没有空值?
【发布时间】:2022-12-17 03:07:55
【问题描述】:

为什么我在 list2 的行中收到警告?我在这里过滤掉了所有的空值。警告指出,在 select 方法中可能会取消引用空值。

#nullable enable

using System.Collections.Generic;
using System.Linq;

namespace Secunet.Bocoa.AtBmi.SecondLineCheckPlugin
{
    public class Test
    {
        public Test()
        {
            List<string?> testList = new List<string?>()
            {
                "hallo",
                null
            };

            IEnumerable<string> list2 = testList.Where(x => x != null).Select(x => x.Replace("A", "")); // warning
            IEnumerable<string> list3 = testList.Where(x => x != null).Select(x => x != null ? x.Replace("A", "") : ""); // no warning
        }
    }
}

这是我在 list2 行中收到的警告:

在 list3 的行中没有发出警告,但是 Select-Statement 中的检查总是没有意义的。

【问题讨论】:

    标签: c# linq nullable-reference-types


    【解决方案1】:

    您会收到警告,因为可枚举中的类型仍然是可为 null 的 string?

    我想有可能另一个线程在枚举期间将 hallo 条目更改为 null,但编译器更有可能不够复杂,无法理解您已经提前过滤掉任何可能的 null 值。

    您可以在过滤掉null 值后使用.Cast&lt;string&gt;() 来更改枚举中的类型。

    【讨论】:

      【解决方案2】:

      尝试声明List&lt;string&gt;,然后在 Where 子句中声明(x =&gt; !string.IsNullOrEmpty(x))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多