gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:21:42 24 4
gpt4 key购买 nike

编译器应该翻译这段代码:

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(公共(public)语言规范,一种指定所有 .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 :) )

(这里问的正是这种情况)

如果你想看ECMA-335标准:

I.8.11.1 Method definitions

The method signature defines the calling convention, type of the parameters to the method, and the return type of the method

如果您有兴趣知道如何调用该方法...那么...显然如果 IL 语言支持按返回类型重载,那么它的 call 指令必须支持它:-)

例如http://goo.gl/CS4FPb :

call int64 MyNumber::op_Explicit(class MyNumber)

对比

call float64 MyNumber::op_Explicit(class MyNumber)

请注意,CLS 通常禁止仅基于返回类型的重载...但是 op_Implicit(隐式转换运算符)和 op_Explicit(显式转换运算符)(来自同一个 ECMA-335 文件):

CLS Rule 38: Properties and methods can be overloaded based only on the number and types of their parameters, except the conversion operators named op_Implicit and op_Explicit, which can also be overloaded based on their return type.

关于c# - C# 编译器如何处理显式转换运算符的重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35867507/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com