gpt4 book ai didi

c# - C#如何选择带歧义和params

转载 作者:可可西里 更新时间:2023-11-01 07:54:15 26 4
gpt4 key购买 nike

假设我有以下方法:

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

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

如果我这样做:

MyCoolMethod("Hi", "test");

哪个被调用,为什么?

最佳答案

很容易测试 - 调用第二个方法。

至于为什么 - C# 语言规范有一些关于如何解决不明确的函数声明的非常详细的规则。有很多关于 SO 周围接口(interface)、继承和重载的问题,以及为什么调用不同重载的一些特定示例,但要回答这个特定实例:

C# Specification - Overload Resolution

7.5.3.2 Better function member

For the purposes of determining thebetter function member, astripped-down argument list A isconstructed containing just theargument expressions themselves in theorder they appear in the originalargument list.

Parameter lists for each of thecandidate function members areconstructed in the following way:

  • The expanded form is used ifthe function member was applicableonly in the expanded form.

  • Optional parameters with nocorresponding arguments are removedfrom the parameter list

  • The parameters are reorderedso that they occur at the sameposition as the corresponding argumentin the argument list.

进一步……

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 followingtie-breaking rules are applied, in order, to determine the better function member.

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

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

  • Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ.This can occur if both methods have params arrays and are applicable only in theirexpanded forms.

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

关于c# - C#如何选择带歧义和params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3190248/

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