简体   繁体   English

c#中隐式转换的顺序

[英]Order of implicit conversions in c#

What is the order of implicit conversions done in Console.WriteLine(x) when x is an object from user-defined class: 当x是来自用户定义的类的对象时,在Console.WriteLine(x)中完成的隐式转换的顺序是什么:

    class Vector
    {
        public int x = 12;       

        public static implicit operator double(Vector v1)
        {
            return 3.14;
        }

        public static implicit operator int(Vector v1)
        {
            return 42;
        }

        public override string ToString()
        {
            return this.x.ToString();
        }

    }

    static void Main(string[] args)
    {
        Vector v11 = new Vector();
        Console.WriteLine(v11);
    }

Why I get 42, and not 3.14 or "12"? 为什么我得到42,而不是3.14或“12”? Why I can not add an additional implicit conversion to string /there is Compiler error on the ambiguity between CW(int) and CW(string)/: 为什么我不能向字符串添加额外的隐式转换/ CW(int)和CW(字符串)/之间存在歧义的编译器错误:

        public static implicit operator string(Vector v1)
        {
            return "42";
        }

I know I should avoid using the implicit cast, but just for curiosity! 我知道我应该避免使用隐式演员,但仅仅是为了好奇!

So what is printed is based entirely on what overload of Console.WriteLine is chosen. 所以打印的内容完全取决于选择Console.WriteLine重载。 Which overload is chosen is based on section 7.5.3.2 of the specs on "betterness" for function members. 选择哪个重载基于函数成员“更好”规范的7.5.3.2节。

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. object是最不具体的重载,因为没有从它到int,double或string的隐式转换,但每种类型都有一个。 int is more specific than double because there's an implicit conversion from int to double, but no conversion from double to int. int比double更具体,因为从int到double的隐式转换,但没有从double到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. int和string之间没有隐式转换,所以两者都没有更具体,所以它们都不比另一个更好或更差。

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. 因此,如果存在从对象到string的隐式转换,则会考虑字符串重载,并且“最佳”重载存在并列,并且您会收到错误。 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. 当它缺失时,所有被考虑的重载(都是int )都是“最具体”类型,因此它是“最好的”,并且选择了重载。

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

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