简体   繁体   English

C#是可空的int可空小数的后代

[英]C# Is nullable int descendant of nullable decimal

I have discovered by error something that surprised me. 我错误地发现了令我惊讶的事情。

I have this method 我有这个方法

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

And I call this method like this 我把这种方法称为这样

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

Why this is working and there are no compilation errors. 为什么这是有效的,没有编译错误。 I'm calling a method witch is defined to receive a decimal? 我正在调用一个定义为接收decimal? with a int? int?

You just discovered something described in the spec as lifted operators . 您刚刚发现规范中描述的内容为提升运算符

They let you convert Nullablt<A> to Nullable<B> as long as A can be converted to B . 只要A可以转换为B它们就可以将Nullablt<A>转换为Nullable<B>

6.4.2 Lifted conversion operators 6.4.2提升转换运营商

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? 给定一个用户定义的转换运算符,它从非可空值类型S转换为非可空值类型T ,存在一个从S?转换的提升转换运算符S? to T? T? . This lifted conversion operator performs an unwrapping from S? 这个提升的转换操作符执行从S?解包S? to S followed by the user-defined conversion from S to T followed by a wrapping from T to T? S后跟用户定义的从ST转换,然后是从TT?的包装T? , except that a null valued S? ,除了nullS? converts directly to a null valued T? 直接转换为nullT? .

This works because int can be implicitly converted to a decimal, and therefore the nullable versions can also be implicitly converted. 这是有效的,因为int可以隐式转换为十进制,因此也可以隐式转换可为空的版本。

FROM   TO
int    long , float, double, or decimal

https://msdn.microsoft.com/en-us/library/y5b434w4.aspx 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 http://blogs.msdn.com/b/ericlippert/archive/2007/06/27/what-exactly-does-lifted-mean.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM