C#参数至少有一个值

时间:2012-05-04 08:57:04

标签: c# parameters

如何让参数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
}

3 个答案:

答案 0 :(得分:27)

只是做:

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

答案 1 :(得分:6)

您无法在编译时为params指定此类条件。

但是,您可以在运行时检查此项,并在未满足指定条件时抛出异常。

答案 2 :(得分:0)

有一种方法可以在编译时至少要求一个参数,但这确实很麻烦。

  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.
    }
  }