隐式运算符优先于ToString()方法吗?

时间:2014-11-29 12:51:54

标签: c# .net clr overloading operator-keyword

请考虑以下代码:

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!"

为什么在前三种情况下,即使我们明确转向42,我们也会回答Testimplicit运算符的优先级高于ToString()吗?

1 个答案:

答案 0 :(得分:1)

是。隐式运算符优先于显式运算符。语言规范声明隐式运算符不应该丢失信息,而显式运算符允许这样做。例如,请参阅MSDN explicit。如果您将关键字implicit更改为explicit,您会看到Test here! 3次,并且会看到42次。

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!"