c# - 为什么 ref 和 out 不足以消除 C# 中重载的歧义?

标签 c# .net methods

例如,为什么这个方法 Max(ref int x, ref int y) 不被认为是 Max(int x, int y) 的重载?为什么和out一样呢?

最佳答案

这个问题预设了一个错误的前提。

 Max(int x, int y)
 Max(ref int x, ref int y) 
 Max(out int x, out int y)

都是名为 Max 的方法的重载。但是,请注意,在任何给定的类定义中只能出现最后两个中的一个。来自规范§3.6:

The signature of a method consists of the name of the method, the number of type parameters and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. For these purposes, any type parameter of the method that occurs in the type of a formal parameter is identified not by its name, but by its ordinal position in the type argument list of the method. The signature of a method specifically does not include the return type, the params modifier that may be specified for the right-most parameter, nor the optional type parameter constraints.

[...]

Although out and ref parameter modifiers are considered part of a signature, members declared in a single type cannot differ in signature solely by ref and out. A compile-time error occurs if two members are declared in the same type with signatures that would be the same if all parameters in both methods with out modifiers were changed to ref modifiers. For other purposes of signature matching (e.g., hiding or overriding), ref and out are considered part of the signature and do not match each other. (This restriction is to allow C# programs to be easily translated to run on the Common Language Infrastructure (CLI), which does not provide a way to define methods that differ solely in ref and out.)

关于c# - 为什么 ref 和 out 不足以消除 C# 中重载的歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6334511/

相关文章:

java - 写入文件java

c# - 尽管产生了意外的堆栈溢出

c# - 在注册表中查找应用程序路径

c# - Unity 不拦截 WCF 服务调用

C# 命名空间通信

java - 该方法创建对象(持久实体)时出错

c# - 向 Autofac 指定要解析的命名服务

c# - 保存 blob 时出现异常

c# - 在 SQL Server 2008 R2 Express 中使用 ServiceStack.OrmLite 的 Unicode 字符串

c# - Libnoise XNA translate perlin 导致失真