C#如何选择歧义和参数 [英] How does C# choose with ambiguity and params

查看:19
本文介绍了C#如何选择歧义和参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下方法:

public static void MyCoolMethod(params object[] allObjects)
{
}

public static void MyCoolMethod(object oneAlone, params object[] restOfTheObjects)
{
}

如果我这样做:

MyCoolMethod("Hi", "test");

哪个被调用,为什么?

推荐答案

测试很容易 - 调用第二种方法.

It's easy to test - the second method gets called.

至于为什么 - C# 语言规范对如何解决不明确的函数声明有一些非常详细的规则.关于 SO 周围的接口、继承和重载有很多问题,还有一些关于为什么不同重载被调用的具体例子,但要回答这个具体实例:

As to why - the C# language specification has some pretty detailed rules about how ambiguous function declarations get resolved. There are lots of questions on SO surrounding interfaces, inheritance and overloads with some specific examples of why different overloads get called, but to answer this specific instance:

C# 规范 - 重载分辨率

7.5.3.2 更好的函数成员

7.5.3.2 Better function member

为了确定更好的功能成员,一个精简的参数列表 A 是构造仅包含参数表达式本身在按它们出现在原件中的顺序参数列表.

For the purposes of determining the better function member, a stripped-down argument list A is constructed containing just the argument expressions themselves in the order they appear in the original argument list.

每个参数的列表候选函数成员是构造方式如下:

Parameter lists for each of the candidate function members are constructed in the following way:

  • 在以下情况下使用扩展形式函数成员适用仅以展开形式.

  • The expanded form is used if the function member was applicable only in the expanded form.

可选参数,无相应的参数被删除来自参数列表

Optional parameters with no corresponding arguments are removed from the parameter list

参数重新排序以便它们同时发生位置作为相应的参数在参数列表中.

The parameters are reordered so that they occur at the same position as the corresponding argument in the argument list.

进一步...

如果参数类型序列 {P1, P2, ..., PN} 和 {Q1, Q2, ..., QN} 是等价的 >(即每个 Pi 都有一个身份转换为相应的 Qi),如下应用打破平局的规则,以确定更好的函数成员.

In case the parameter type sequences {P1, P2, …, PN} and {Q1, Q2, …, QN} are equivalent > (i.e. each Pi has an identity conversion to the corresponding Qi), the following tie-breaking rules are applied, in order, to determine the better function member.

  • 如果 MP 是非泛型方法而 MQ 是泛型方法,那么 MP 优于 MQ.

  • If MP is a non-generic method and MQ is a generic method, then MP is better than MQ.

否则,如果 MP 以其正常形式适用并且 MQ 有一个 params 数组并且是仅适用于展开形式,则 MP 优于 MQ.

Otherwise, if MP is applicable in its normal form and MQ has a params array and is applicable only in its expanded form, then MP is better than MQ.

否则,如果 MP 的声明参数比 MQ 多,那么 MP 就比 MQ 好.如果这两种方法都有 params 数组并且仅适用于它们的扩展表单.

粗体打破平局规则似乎适用于这种情况.规范详细说明了如何以正常和扩展形式处理 params 数组,但最终的经验法则是,将根据参数的数量和类型调用最具体的重载.

The bolded tie-breaking rule seems to be what is applying in this case. The specification goes into detail about how the params arrays are treated in normal and expanded forms, but ultimately the rule of thumb is that the most specific overload will be called in terms of number and type of parameters.

这篇关于C#如何选择歧义和参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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