微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

参见英文答案 > Order of implicit conversions in c#                                    1个
请考虑以下代码

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?
隐式运算符优先于ToString()吗?

解决方法

是.隐式运算符优先于显式运算符.语言规范声明隐式运算符不应该丢失信息,而显式运算符允许这样做.例如,参见 MSDN explicit.如果将隐式关键字更改为显式,您将在此处看到Test! 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!"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐