考虑这个通用的恒等函数:
T Id<T>(T x) => x;
如果我在 lambda 中使用它来映射值数组中的元素string?
,它会按预期工作(即它保留信息,即值可以为空)。
var xs = new[] { (string?)"foo" };
var ys = xs.Select(x => Id(x)); // inferred type of `ys` is IEnumerable<string?>
string y = ys.Single(); // warning CS8600: Converting [...] possible null value to non-nullable type.
但是,如果我将其用作方法组,则该信息将被丢弃。
var xs = new[] { (string?)"foo" };
var ys = xs.Select(Id); // inferred type of `ys` is IEnumerable<string>
string y = ys.Single(); // no warning CS8600
这里发生了什么?这是编译器错误还是可空引用类型的已知限制?
作为一种解决方法,我可以Id
像下面这样声明以获得第二个示例中的预期警告:
T? Id<T>(T? x) => x;
但这对我来说似乎过于富有表现力。
我正在使用 C# 10.0。