简体   繁体   English

解决C#中的params

[英]Resolving params in C#

What are the rules when resolving variable number of parameters passed by params ? 解析params传递的可变参数数量时有哪些规则?

Suppose, that I have the code: 假设我有代码:

public void Method(params object[] objects) { }

public void Method(IMyInterface intf, params object[] objects) { }

How is Method(a, b, c) resolved, if a is a IMyInterface? 如果a是IMyInterface, Method(a, b, c)解决? Can I be sure, that C# will always try to select most matching overload? 我可以确定,C#总是会尝试选择大多数匹配的重载吗?

This is answered by the C# language spec: 这可以通过C#语言规范来回答:

7.5.3.1 Applicable function member 7.5.3.1适用的功能成员

[...] [...]

  • Otherwise, if MP is applicable in its normal form and MQ has a params array and is applicable only in its expanded form, then MP is better than MQ. 否则,如果MP以其正常形式适用且MQ具有params数组并且仅适用于其扩展形式,则MP优于MQ。

  • Otherwise, if MP has more declared parameters than MQ, then MP is better than MQ. 否则,如果MP具有比MQ更多的声明参数,则MP优于MQ。 This can occur if both methods have params arrays and are applicable only in their expanded forms. 如果两个方法都具有params数组并且仅适用于它们的扩展形式,则会发生这种情况。

[...] [...]

In your example both overloads would be applicable only in their expanded forms. 在您的示例中,两个重载仅适用于其扩展形式。 Since the second has more declared parameters it would be better . 由于第二个具有更多声明的参数,因此会更好

In the context of the spec, one overload being better than all the others means that the compiler selects it to bind the call, as would happen in the example under discussion (if no one overload is better than all the others, the result is a compile-time error due to ambiguity). 在规范的上下文中,一个重载优于所有其他重载意味着编译器选择它来绑定调用,正如在讨论的示例中所发生的那样(如果没有一个重载优于所有其他重载,则结果是由于模糊而导致的编译时错误)。

See also C# Spec. 另见C#Spec。 17.5.1.4 regarding Parameter arrays 17.5.1.4关于参数数组

When performing overload resolution, a method with a parameter array may be applicable either in its normal form or in its expanded form (§14.4.2.1). 执行重载决策时,带参数数组的方法可以以其正常形式或以其扩展形式(第14.4.2.1节)应用。 2 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. 2只有在方法的正常形式不适用且仅与扩展形式具有相同签名的方法尚未在同一类型中声明时,方法的扩展形式才可用。

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);  
   }  
}  

produces the output: 产生输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM