C# 是 nullable decimal 的 nullable int 后代

C# Is nullable int descendant of nullable decimal

我错误地发现了一些让我吃惊的东西。

我有这个方法

public static string PrintDecimal(decimal? input, string NumberFormat = null){ }

我这样调用这个方法

int? MaxFaltas = 0;
Label.Text = CustomConvert.PrintDecimal(MaxFaltas);

为什么这行得通并且没有编译错误。我调用的方法 被定义为接收带有 int?

decimal?

之所以可行,是因为 int 可以隐式转换为小数,因此也可以隐式转换可为 null 的版本。

FROM   TO
int    long , float, double, or decimal

https://msdn.microsoft.com/en-us/library/y5b434w4.aspx

http://blogs.msdn.com/b/ericlippert/archive/2007/06/27/what-exactly-does-lifted-mean.aspx

您刚刚发现了规范中描述为 lifted operators 的内容。

他们让你把Nullablt<A>转换成Nullable<B>只要A可以转换成B

6.4.2 Lifted conversion operators

Given a user-defined conversion operator that converts from a non-nullable value type S to a non-nullable value type T, a lifted conversion operator exists that converts from S? to T?. This lifted conversion operator performs an unwrapping from S? to S followed by the user-defined conversion from S to T followed by a wrapping from T to T?, except that a null valued S? converts directly to a null valued T?.