隐式运算符是否比ToString()方法具有更高的优先级? [英] Does implicit operator have higher priority over ToString() method?

查看:99
本文介绍了隐式运算符是否比ToString()方法具有更高的优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

为什么在前三种情况下,即使我们显式转换为Test,我们仍会回答42?
implicit运算符的优先级是否高于ToString()?

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() ?

推荐答案

是.隐式运算符的优先级高于显式运算符.语言规范指出,隐式运算符不应丢失信息,而显式运算符则允许这样做.例如,请参见 MSDN明确.如果将关键字implicit更改为explicit,您会看到3次Test here!,一次出现42次.

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

这篇关于隐式运算符是否比ToString()方法具有更高的优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆