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

我的未来我决定 提交于 2019-12-05 12:20:23

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