2

我有这个测试代码:

    void func1(string a, params string[] p)
    {
        func1(a, true, p);
    }

    void func1(string a, bool b, params string[] p)
    {
        //...
    }

    void func2(string a, bool b = true, params string[] p)
    {
        //...
    }

    void exec()
    {
        func1("a", "p1", "p2");
        func2("a", "p1", "p2");
    }

func1func2等于?

创建时没有错误func2,但是,当我尝试func2在 exec 中使用 like (使用可选值)时,编译器会显示错误This function has some invalid arguments

我认为这对于像 API 一样使用这个函数的人来说是平等的func1func2

这段代码有什么问题?我可以将此方法用于具有可选和参数值的函数吗?

4

1 回答 1

10

Normally optional parameters have to come at the end of a method declaration - a parameter array (such as p here) is the only exception to that. But when it comes to using the arguments, the compiler will assume that all positional arguments are in the same order as the method declaration... so you get into trouble if you want to use the optionality and the parameter array side. This should be okay:

func2("a", p: new[] { "p1", "p2" })

but personally I'd just steer clear of mixing parameter arrays and optional parameters. It's clearly confusing.

I believe the relevant section of the C# 5 specification is 7.5.1.1, which includes:

A positional argument of a function member with a parameter array invoked in its expanded form, where no fixed parameter occurs at the same position in the parameter list, corresponds to an element of the parameter array.

See also section 7.5.3.1. It's all pretty complicated...

于 2013-02-08T17:00:56.217 回答