代码之家  ›  专栏  ›  技术社区  ›  Jouke van der Maas

或多或少相等的重载

  •  11
  • Jouke van der Maas  · 技术社区  · 14 年前

    以下代码在C 4.0中编译:

    void Foo(params string[] parameters) { }
    void Foo(string firstParameter, params string[] parameters) { }
    

    2 回复  |  直到 14 年前
        1
  •  13
  •   Hans Passant    14 年前

    It is well specified in the C# Language Specification, chapter 7.4.3.2, "Better function member":

    否则,如果MP以其正常形式适用,并且MQ具有参数数组,并且仅以其扩展形式适用,则MP优于MQ。

    Otherwise, if MP has fewer 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.

    Fwiw, the C# Language Specification is a 非常 readable document and can help you resolve these puzzles by yourself. You have it on your machine, find it back in the Visual Studio install directory (like c:\program files\microsoft visual studio 9.0) in the vc#\specifications\1033 subdirectory.

    另一个好的文件是ECMA-335标准文件,作为 PDF download

        2
  •  6
  •   Mau    14 年前

    在某些情况下, it will decide for you . So, you might want to use different names in cases like this (or in more useful cases :-) ).

    In particular, out of the four cases:

            Foo("bar");
            Foo("bar", "bar");
            Foo(new string[]{"bar", "bar"});
            Foo("bar", new string[] { "bar", "bar" });
    

    only #1 and #2 are 'ambiguous' (since #3 and #4 naturally match overload 1 and 2 respectively).

    In cases #1 and #2 overload resolution chooses overload #2, because it has a standalone string parameter that matches the only/first parameter of the invocation.