C#:方法签名?
假设我创建了这两个方法:
public void AddScriptToPage(params string[] scripts) { /*...*/ }
public void AddScriptToPage(string href, string elementId) { /*...*/ }
下面的代码将调用其中哪一个方法,为什么?
AddScriptToPage("dork.js", "foobar.js");
编译器如何确定调用哪个方法?
Let's say I create these two methods:
public void AddScriptToPage(params string[] scripts) { /*...*/ }
public void AddScriptToPage(string href, string elementId) { /*...*/ }
Which one of these methods gets call by the code below, and why?
AddScriptToPage("dork.js", "foobar.js");
How does the compiler determine which method to call?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的第二个方法被调用,如果找到完全匹配,则在参数之前使用它。
来自 MSDN:
执行重载解析时,带有参数数组的方法可以以其正常形式或以其扩展形式应用(第 7.4.2.1 节)。仅当方法的正常形式不适用并且仅当尚未在同一类型中声明与扩展形式具有相同签名的方法时,方法的扩展形式才可用。
他们的例子:
输出:
Your second method gets called, if an exact match is found, it's used before params.
From MSDN:
When performing overload resolution, a method with a parameter array may be applicable either in its normal form or in its expanded form (Section 7.4.2.1). The expanded form of a method is available only if the normal form of the method is not applicable and only if a method with the same signature as the expanded form is not already declared in the same type.
Their example:
Output:
..会被叫到。编译器选择最准确匹配的签名,而参数的优先级最低。
.. will get called. The compiler chooses the signature with the most accurate match, with params having least priority.