首页 > 解决方案 > Rider Bug - C# 8 Nullable 引用参数上的扩展方法显示警告

问题描述

已解决 Turns our Rider (2019.1) 错误地显示此警告,但没问题dotnet build。它已在 v2019.2 中修复

我有一个可为空的属性MainBgColor

public class Provider
{
   public string? MainBgColor { get; set; }
}

我有一个扩展方法,string.Empty如果输入为空则返回。

public static string EmptyIfNull(this string input) => input ?? string.Empty;

但是当我尝试使用它时

var provider = GetTheProviderSomehow();
var logo = provider.MainBgColor.EmptyIfNull();

我收到 c#8 编译器生成的警告

[CS8604] Possible null reference argument for parameter 'input' in 'string ProviderExtensions.EmptyIfNull(string input)'.

我的问题是,这会很好,因为我正在检查 null(在扩展方法内)而没有启用可为空的引用类型功能。为什么它还在抱怨?

如果我将扩展方法更改为允许nullable string?- 那么编译器认为它不是provider.Logo.

在此处输入图像描述

这是 C#8 可空引用类型的预期功能吗?我不应该对其中一种可为空的类型使用扩展方法吗?

标签: c#riderc#-8.0nullable-reference-types

解决方案


您需要将扩展​​方法声明为接受可为空的字符串。


推荐阅读