【问题标题】:Conversion rules for overloaded conversion operators重载转换运算符的转换规则
【发布时间】:2013-02-08 17:00:28
【问题描述】:

给定以下代码:

using System;

namespace Test721
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(new A()); //prints 666
            Console.WriteLine(new B()); //prints 666
            Console.ReadLine();
        }
    }

    public class A
    {
        public static implicit operator int(A a)
        {
            return 666;
        }
    }

    public class B : A
    {
        public static implicit operator double(B b)
        {
            return 667;
        }
    }
}

结果与 cmets 中的一样 - 两行都打印 666。

我希望 Console.WriteLine(new B()); 写 667,而 double 重载 Console.WriteLine

为什么会这样?

【问题讨论】:

    标签: c# operator-overloading


    【解决方案1】:

    这在 3.5 C# 语言规范的第 7.4.3.4 节中有介绍。本节介绍重载解决方案以及在此过程中如何考虑转换。适用行是

    如果存在从 T1 到 T2 的隐式转换,并且不存在从 T2 到 T1 的隐式转换,则 C1 是更好的转换。

    在这种情况下,存在从 Bint (T1) 和 double (T2) 的隐式转换。存在从 intdouble 的隐式转换,但反之则不然。因此,从Bint 的隐式转换被认为更好并获胜。

    【讨论】:

    • 我能想到的最佳答案,谢谢。当 SO 允许我接受时,我会在一分钟内接受;]
    • 假设这些规则会使编译器认为float 优于double,我是否正确?那看起来非常棒。
    【解决方案2】:

    由于您没有指定将值转换为编译器正在做什么

    Console.WriteLine((int)(new B()));
    

    你应该改用下面的

    Console.WriteLine((double)(new B()));
    

    【讨论】:

    • 是的,编译器正在这样做,但 OP 询问“为什么”编译器正在这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2013-11-21
    • 1970-01-01
    相关资源
    最近更新 更多