在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;
}