C#中的隐式转换顺序 [英] Order of implicit conversions in c#

查看:136
本文介绍了C#中的隐式转换顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当x是用户定义类的对象时,在Console.WriteLine(x)中完成隐式转换的顺序是什么:

What is the order of implicit conversions done in Console.WriteLine(x) when x is an object from user-defined class:

    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);
    }

为什么我得到42,而不是3.14或"12"?为什么我不能向字符串添加额外的隐式转换/为什么在CW(int)和CW(string)/之间存在编译器错误:

Why I get 42, and not 3.14 or "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)/:

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

我知道我应该避免使用隐式强制转换,而只是出于好奇!

I know I should avoid using the implicit cast, but just for curiosity!

推荐答案

所以打印的内容完全基于选择了Console.WriteLine的重载.选择哪种重载基于功能成员更好"规范的第7.5.3.2节.

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是最不明确的重载,因为没有从它到int,double或string的隐式转换,但每种类型都有一个隐式转换. int比double更具体,因为存在从int到double的隐式转换,但是没有从double到int的转换. int和string之间没有隐式转换,因此两者都不是更具体的,因此彼此之间也不会有更好或更差的结果.

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.

因此,如果存在从您的对象到string的隐式转换,则将考虑字符串重载,并且存在最佳"重载的关系,并且会出现错误.当缺少它时,在所有考虑的重载中都有一个最特定的"类型(int),因此它是最好的",并选择了该重载.

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.

这篇关于C#中的隐式转换顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆