在 C# 8 中,应将引用类型显式标记为可为空。
默认情况下,这些类型不能包含 null,有点类似于值类型。虽然这不会改变引擎盖下的工作方式,但类型检查器将要求您手动执行此操作。
给定的代码被重构以使用 C# 8,但它并没有从这个新特性中受益。
public static Delegate? Combine(params Delegate?[]? delegates)
{
// ...[]? delegates - is not null-safe, so check for null and emptiness
if (delegates == null || delegates.Length == 0)
return null;
// Delegate? d - is not null-safe too
Delegate? d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
d = Combine(d, delegates[i]);
return d;
}
这是利用此功能的更新代码示例(不起作用,只是一个想法)。它使我们免于进行空值检查,并稍微简化了此方法。
public static Delegate? Combine(params Delegate[] delegates)
{
// `...[] delegates` - is null-safe, so just check if array is empty
if (delegates.Length == 0) return null;
// `d` - is null-safe too, since we know for sure `delegates` is both not null and not empty
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
// then here is a problem if `Combine` returns nullable
// probably, we can add some null-checks here OR mark `d` as nullable
d = Combine(d, delegates[i]);
return d;
}