<分区>
让我们从一段非常简单的代码开始:
decimal d = 2;
Console.WriteLine("d == 2 = {0}", d == 2);
Console.WriteLine("d == (decimal)2 = {0}", d == (decimal)2);
Console.WriteLine("d.Equals(2) = {0}", d.Equals(2));
Console.WriteLine("d.Equals((decimal)2) = {0}", d.Equals((decimal)2));
结果是 4xtrue。现在,让我们将变量 d 的类型更改为 decimal?:
decimal? d = 2;
这次结果将是真、真、假、真。这种情况的解释很容易。 Equals 方法对于 Nullable
public override bool Equals(object other)
{
if (!this.HasValue)
{
return (other == null);
}
if (other == null)
{
return false;
}
return this.value.Equals(other);
}
如果 this 有一个值并且 other 参数不为空,则 Decimal.Equals(object value) 将被调用。 Decimal.Equals(object value) 方法以这种方式工作,如果 value 参数不是 decimal 那么结果将始终是 错误的。
在我看来,当前的实现并不直观,我想知道为什么 Nullable
public bool Equals(T other)
{
if (!this.HasValue)
return false;
return this.value.Equals(other);
}
是故意为之还是疏忽?
评论 1:
要清楚的简短评论。我建议 Nullable