C# 使用 params 修饰符重载方法
C# Overloading of methods with params modifier
我有如下两种方法
int foo (int a, param int[] b); // f1
int foo (params int[] a); // f2
在扩展形式中我怎么能调用f1
?
信息:
当我使用 扩展形式时 foo (1, 2)
这会调用 f2
。我需要明确地使用 正常形式 foo (1, new [] {2})
来调用 f1
我正在使用 Mono C# compiler version 4.6.2.0
- https://repl.it/Fy4L
int f(int i, params int[] a) { return 1; } // 1
int f( params int[] a) { return 2; } // 2
然后你可以做几个测试:
Debug.Print("" + f(1) ); // 1
Debug.Print("" + f(1, 2) ); // 1 (2 in Mono?)
Debug.Print("" + f(1, new int[] { })); // 1
Debug.Print("" + f() ); // 2
Debug.Print("" + f(new int[] { } ) ); // 2
Debug.Print("" + f(new int[] { 1, 2 }) ); // 2
阅读 https://www.microsoft.com/en-us/download/confirmation.aspx?id=7029 处的 C#5 语言规范,我们发现以下内容:
"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 their expanded forms"
-第 7.5.3.2 节
MQ和MP指的是重载决议中的候选方法。扩展形式指的是params 数组被扩展为一系列参数(即当params 部分被使用时)。
这意味着在这个版本的规范中,如果您有更多声明的参数(f1 有),那么它将是更好的候选者。
虽然我没有检查规范的所有版本,但凭记忆总是如此。在任何时候更改此行为都将是一个重大更改,我 99.99% 确定编译器团队不会这样做(感谢 @xanatos 在评论中指出这一点)。我相信答案是在你的代码中它应该选择 f1 作为正确的重载并且单声道中的错误导致你看到的行为。
这似乎得到了@xanatos 发现的https://bugzilla.xamarin.com/show_bug.cgi?id=6541 的支持(再次感谢)。错误示例代码使用字符串,但问题相同。
我有如下两种方法
int foo (int a, param int[] b); // f1
int foo (params int[] a); // f2
在扩展形式中我怎么能调用f1
?
信息:
当我使用 扩展形式时 foo (1, 2)
这会调用 f2
。我需要明确地使用 正常形式 foo (1, new [] {2})
来调用 f1
我正在使用 Mono C# compiler version 4.6.2.0
- https://repl.it/Fy4L
int f(int i, params int[] a) { return 1; } // 1
int f( params int[] a) { return 2; } // 2
然后你可以做几个测试:
Debug.Print("" + f(1) ); // 1
Debug.Print("" + f(1, 2) ); // 1 (2 in Mono?)
Debug.Print("" + f(1, new int[] { })); // 1
Debug.Print("" + f() ); // 2
Debug.Print("" + f(new int[] { } ) ); // 2
Debug.Print("" + f(new int[] { 1, 2 }) ); // 2
阅读 https://www.microsoft.com/en-us/download/confirmation.aspx?id=7029 处的 C#5 语言规范,我们发现以下内容:
"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 their expanded forms"
-第 7.5.3.2 节
MQ和MP指的是重载决议中的候选方法。扩展形式指的是params 数组被扩展为一系列参数(即当params 部分被使用时)。
这意味着在这个版本的规范中,如果您有更多声明的参数(f1 有),那么它将是更好的候选者。
虽然我没有检查规范的所有版本,但凭记忆总是如此。在任何时候更改此行为都将是一个重大更改,我 99.99% 确定编译器团队不会这样做(感谢 @xanatos 在评论中指出这一点)。我相信答案是在你的代码中它应该选择 f1 作为正确的重载并且单声道中的错误导致你看到的行为。
这似乎得到了@xanatos 发现的https://bugzilla.xamarin.com/show_bug.cgi?id=6541 的支持(再次感谢)。错误示例代码使用字符串,但问题相同。