Order of implicit conversions in c#

☆樱花仙子☆ 提交于 2019-12-01 15:49:17

So what is printed is based entirely on what overload of Console.WriteLine is chosen. Which overload is chosen is based on section 7.5.3.2 of the specs on "betterness" for function members.

An overload is "better" than another, when it has a parameter that is "more specific" than another one. "more specific" means there's an implicit conversion from the more specific type to the less specific type, and no implicit conversion from the less specific type to the more specific type.

object is the least specific overload, as there's no implicit conversion from it to int, double, or string, but there is one from every type to it. int is more specific than double because there's an implicit conversion from int to double, but no conversion from double to int. int and string have no implicit conversions between each other, so neither is more specific, and so neither is better or worse than the other.

So if there's an implicit conversion from your object to string then the string overload is considered, and there's a tie for "best" overload, and you get an error. When it's missing there's a "most specific" type of all of the considered overloads (which is int), so it's "the best", and that overload is chosen.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!