首页 > 解决方案 > 你能有带有限制条件的可选参数吗?

问题描述

我想创建一个有两个可选参数的函数,但你只能选择两个可选参数之一。

例如:

 public void DoThing (int foo = 0, string bar = "test") {
    if (foo != 0)      // Do something with foo
    if (bar != "test") // Do something with bar
 }

但是,如果有人这样做DoThing(1, "Hello World!");,它将调用这两种状态,我不想让他们同时使用这两种状态。

是否可以强制他们在编译代码之前修复这个错误?

标签: c#optional-parameters

解决方案


为什么不超载

public void DoThing (int foo) {
  // Do something with foo
}

public void DoThing (string bar) {
  // Do something with bar
}

public void DoThing (int foo, string bar) {
  // Do something with foo and bar
}

推荐阅读