Does implicit operator have higher priority over T

2019-05-07 01:15发布

This question already has an answer here:

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条回答
迷人小祖宗
2楼-- · 2019-05-07 01:48

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!"
查看更多
登录 后发表回答