具有null的数学运算 [英] Math operations with null
问题描述
请解释为什么该测试通过?
Please explain why this test passes?
[Test]
public void TestNullOps()
{
Assert.That(10 / null, Is.Null);
Assert.That(10 * null, Is.Null);
Assert.That(10 + null, Is.Null);
Assert.That(10 - null, Is.Null);
Assert.That(10 % null, Is.Null);
Assert.That(null / 10, Is.Null);
Assert.That(null * 10, Is.Null);
Assert.That(null + 10, Is.Null);
Assert.That(null - 10, Is.Null);
Assert.That(null % 10, Is.Null);
int zero = 0;
Assert.That(null / zero, Is.Null);
}
我不明白这段代码是如何编译的.
I don't understand how this code even compiles.
每个具有null的数学表达式看起来都返回 Nullable< T>
(例如, 10/null
是 Nullable< int>
).但是我在 Nullable< T>
类中看不到运算符方法.如果这些运算符来自 int
,为什么最后一个断言不会失败?
Looks like each math expression with null returns Nullable<T>
(e.g. 10 / null
is a Nullable<int>
). But I don't see operator methods in Nullable<T>
class. If these operators are taken from int
, why the last assertion doesn't fail?
推荐答案
来自可为null的类型也可以使用预定义的一元和二进制运算符以及为值类型存在的任何用户定义的运算符.如果操作数为null,则这些运算符将产生null值;否则,操作员将使用包含的值来计算结果.
The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if the operands are null; otherwise, the operator uses the contained value to calculate the result.
这就是为什么要通过所有测试(包括最后一个测试)的原因-无论操作数是什么,如果另一个操作数为 null
,则结果为 null
.
That's why all the test are passed, including the last one - no matter what the operand value is, if another operand is null
, then the result is null
.
这篇关于具有null的数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!