我刚开始写一个组件,我发现声明一些属性可为空可能很有用,而不是让它们求助于默认值。但是,我意识到我以前从未使用过 non-nullable-type?
语法或 Nullable<T>
之前打字,所以可能会有一些陷阱很快就会跳出来咬我。所以……
使用
Nullable<T>
时最大的陷阱是什么?和速记?
语法?我该如何解决它们?
当我开始使用它们时,它们给我带来的最大优势/新可能性是什么?
最佳答案
一个常见的陷阱是尝试使用条件表达式分配给可为空的变量,如下所示:
bool useDefault = true;
int defaultValue = 50;
int? y = useDefault ? defaultValue : null;
乍一看这可能看起来应该有效,但实际上它给出了一个编译错误:
Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and '<null>'
Solution: add a cast to one or both of the possible outcomes:
int? y = useDefault ? defaultValue : (int?)null;
不太常见:通常可以安全地假设整数 a <= 5
和 !(a > 5)
是等价的。对于可为 null 的整数,此假设不成立。
int? x = null;
Console.WriteLine(x <= 5);
Console.WriteLine(!(x > 5));
结果:
False True
Solution: Handle the null case separately.
Here's another slight variation of the above:
int? y = null;
int? z = null;
Console.WriteLine(y == z);
Console.WriteLine(y <= z);
输出:
True False
所以 y
等于 z
, 但它不小于或等于 z
.
解决方案:同样,单独处理 null 情况可以避免意外。
关于c# - 在 C# 4 中使用 Nullable<T> 时遇到的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3285495/