24

我怎样才能有一个params至少有一个值的参数?

public void Foo(params string[] s) { }

public void main()
{
    this.Foo(); // compile error
    this.Foo(new string[0]); // compile error
    this.Foo({ }); // compile error
    this.Foo("foo"); // no error
    this.Foo("foo1", "foo2"); // no error
}
4

4 回答 4

41

做就是了:

public void Foo(string first, params string[] s) { }
于 2012-05-04T08:58:10.863 回答
8

您不能params在编译时指定此类条件。

但是,您可以在运行时检查这一点,如果不满足您指定的条件,则抛出异常。

于 2012-05-04T09:13:02.440 回答
1

有一种方法可以在编译时要求至少一个参数,但这真的很hacky。

  public class RequireAtLeastOneParam {
    public string Foo(params string[] args) 
      => string.Join(' ', args);

    /// <summary>The purpose of this overload is to require at least one argument
    /// on any call to Foo. Because this overload exists, call with no arguments won't compile.</summary>
    public string Foo(params char[] args)
      => Foo(args.Select(x => x.ToString()).ToArray());

    public void WontCompile() {
      string foo = Foo(); // compilation fails because this is ambiguous between the two overloads.
    }
  }
于 2020-09-13T13:17:52.073 回答
0

要完成接受的答案:

public void Foo(string bar, params string[] bars)
{
    string[] strs = new string[] { bar }.Concat(bars).ToArray();
}
于 2022-01-27T14:27:54.587 回答