为什么ref和out不足以消除C#中的重载歧义? [英] Why ref and out are not sufficient to disambiguate overloaded in C#?

查看:136
本文介绍了为什么ref和out不足以消除C#中的重载歧义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,为什么不将此方法Max(ref int x, ref int y)视为Max(int x, int y)的重载?为什么与out相同?

For example, why this method Max(ref int x, ref int y) is not considered overload of Max(int x, int y)? Why is the same with out?

推荐答案

这个问题的前提是错误的.

This question presupposes a false premise.

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

是名为Max的方法的所有重载.但是,请注意,任何给定的类定义中只能存在最后两个中的一个.根据规范§3.6:

are all overloads of a method named Max. However, note that only one of the last two may be present in any given class definition. From the specification §3.6:

方法的签名由方法的名称,类型参数的数量以及每个形式参数的类型和类型(值,引用或输出)组成,按从左到右的顺序进行考虑.为此,以形式形参类型出现的方法的任何类型形参不是由其名称标识,而是由其在方法的类型实参列表中的序号位置标识.方法的签名特别不包括返回类型,可能为最右边的参数指定的params修饰符,也不包括可选的类型参数约束.

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.

[...]

尽管outref参数修饰符被视为签名的一部分,但是以单一类型声明的成员不能仅通过refout来进行签名方面的区别.如果将两个成员声明为具有相同签名的相同类型,则将两个方法中都使用out修饰符的所有参数都更改为ref修饰符时,将具有相同的签名,则会发生编译时错误.出于签名匹配的其他目的(例如,隐藏或覆盖),refout被视为签名的一部分,并且彼此不匹配. (此限制是为了使C#程序可以轻松转换为在公共语言基础结构(CLI)上运行,而后者没有提供定义仅在refout中不同的方法的方法.)

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.)

这篇关于为什么ref和out不足以消除C#中的重载歧义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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