gpt4 book ai didi

c# - null 动态变量和函数重载

转载 作者:IT王子 更新时间:2023-10-29 04:48:54 26 4
gpt4 key购买 nike

示例代码:

private void DoSomething(object obj)
{
MessageBox.Show("called object");
}

private void DoSomething(params object[] obj)
{
MessageBox.Show("called object[]");
}


private void button1_Click(object sender, EventArgs e)
{
decimal? amount = null;
dynamic obj = amount;

DoSomething(obj);
}

单击按钮 1 时,将显示消息“调用的对象[]”。似乎在此示例中首选带有 object[] 参数的重载方法。任何想法为什么?我只是好奇胜过一切。

(背景:此行为在具有动态 View 的 Razor 中导致了一些意外结果 Formatting nullable decimal in RazorEngine ).

最佳答案

那是因为您可以将 object[] 转换为 object 而不是相反。 object[] 更具体,因此在方法解析中更受欢迎。

7.5.3.2 Better function member

(...)

Given an argument list A with a set of argument expressions { E1, E2, ..., EN } and two applicable function members MP and MQ with parameter types { P1, P2, ..., PN } and { Q1, Q2, ..., QN }, MP is defined to be a better function member than MQ if

  • for each argument, the implicit conversion from EX to QX is not better than the implicit conversion from EX to PX, and
  • for at least one argument, the conversion from EX to PX is better than the conversion from EX to QX.

随后定义了更好的转化目标:

7.5.3.5 Better conversion target

Given two different types T1 and T2, T1 is a better conversion target than T2 if at least one of the following holds:

  • An implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists

(...)

在您的示例中,T1object[]T2object

关于c# - null 动态变量和函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30092902/

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