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

前端之家收集整理的这篇文章主要介绍了C#编译器如何处理重载显式转换运算符?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
编译器应该翻译这段代码
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

猜你在找的C#相关文章