Does implicit operator have higher priority over ToString() method? [duplicate]

早过忘川 提交于 2020-01-02 05:22:09

问题


Consider the following code:

public class Test
{
    public static implicit operator int(Test t) { return 42; }
    public override string ToString() { return "Test here!"; }
}

var test = new Test();
Console.WriteLine(test); // 42
Console.WriteLine((Test)test); // 42
Console.WriteLine((int)test); // 42
Console.WriteLine(test.ToString()); // "Test here!"

Why in the first three cases we have answer 42 even if we explicitly cast to Test?
Does implicit operator have higher priority over ToString() ?


回答1:


Yes. Implicit operators have precedence over explicit operators. The language specification states that implicit operators should not loose information, while this is allowed for explicit operators. See for instance, MSDN explicit. If you change the keyword implicit to explicit you will see Test here! 3 times, and 42 once.

public class Test
{
    public static explicit operator int(Test t) { return 42; }
    public override string ToString() { return "Test here!"; }
}

var test = new Test();
Console.WriteLine(test); // "Test here!"
Console.WriteLine((Test)test); // "Test here!"
Console.WriteLine((int)test); // 42
Console.WriteLine(test.ToString()); // "Test here!"


来源:https://stackoverflow.com/questions/27202473/does-implicit-operator-have-higher-priority-over-tostring-method

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