C#:方法签名?

发布于 2024-08-19 08:30:53 字数 300 浏览 4 评论 0原文

假设我创建了这两个方法:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愁杀 2024-08-26 08:30:53

您的第二个方法被调用,如果找到完全匹配,则在参数之前使用它。

来自 MSDN

执行重载解析时,带有参数数组的方法可以以其正常形式或以其扩展形式应用(第 7.4.2.1 节)。仅当方法的正常形式不适用并且仅当尚未在同一类型中声明与扩展形式具有相同签名的方法时,方法的扩展形式才可用。

他们的例子:

using System;
class Test
{
   static void F(params object[] a) {
      Console.WriteLine("F(object[])");
   }
   static void F() {
      Console.WriteLine("F()");
   }
   static void F(object a0, object a1) {
      Console.WriteLine("F(object,object)");
   }
   static void Main() {
      F();
      F(1);
      F(1, 2);
      F(1, 2, 3);
      F(1, 2, 3, 4);
   }
}

输出:

F();
F(object[]);
F(object,object);
F(object[]);
F(object[]);

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:

using System;
class Test
{
   static void F(params object[] a) {
      Console.WriteLine("F(object[])");
   }
   static void F() {
      Console.WriteLine("F()");
   }
   static void F(object a0, object a1) {
      Console.WriteLine("F(object,object)");
   }
   static void Main() {
      F();
      F(1);
      F(1, 2);
      F(1, 2, 3);
      F(1, 2, 3, 4);
   }
}

Output:

F();
F(object[]);
F(object,object);
F(object[]);
F(object[]);
月下凄凉 2024-08-26 08:30:53
public void AddScriptToPage(string href, string elementId) 

..会被叫到。编译器选择最准确匹配的签名,而参数的优先级最低。

public void AddScriptToPage(string href, string elementId) 

.. will get called. The compiler chooses the signature with the most accurate match, with params having least priority.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文