加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#编译器如何处理重载显式转换运算符?

发布时间:2020-12-15 04:27:30 所属栏目:百科 来源:网络整理
导读:编译器应该翻译这段代码: public static explicit operator Int64(MyNumber n){ return n.ToInteger();}public static explicit operator Double(MyNumber n){ return n.ToDouble();} 两种方法具有相同的名称和签名,但只有它们的返回类型不同,例如 public s
编译器应该翻译这段代码:
public static explicit operator Int64(MyNumber n)
{
    return n.ToInteger();
}

public static explicit operator Double(MyNumber n)
{
    return n.ToDouble();
}

两种方法具有相同的名称和签名,但只有它们的返回类型不同,例如

public static Int64 ExplicitCast(MyNumber n)
...

public static Double ExplicitCast(MyNumber n)
...

但是,我们不允许只有返回类型的方法.窗帘后面会发生什么?

解决方法

从技术上讲,CLS(公共语言规范,指定所有.NET语言应支持的.NET虚拟机的子部分的规范)表示显式强制转换方法的名称应为op_Explicit(参见例如 http://goo.gl/wn8dHq).

您不能拥有多个具有相同名称且只有不同返回类型的方法的限制是C#的限制. IL语言(即.NET虚拟机的语言)没有此限制.

参见例如:https://stackoverflow.com/a/442100/613130

Some languages (such as MSIL),however,do allow overloading by return type. They too face the above difficulty of course,but they have workarounds,for which you’ll have to consult their documentation.

和https://blogs.msdn.microsoft.com/abhinaba/2005/10/07/c-cil-supports-overloading-by-return-type/

However,CIL does support overloading methods by return types,even though C#,VB does not . To implement convertion operator overloading C# compiler uses this feature (I know of one usage and I’m sure that there are more

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读