问题
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