【问题标题】:Can you have optional parameters with a limiting condition?你能有带有限制条件的可选参数吗?
【发布时间】:2018-07-09 20:52:01
【问题描述】:

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

例如:

 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!");,它会调用这两种状态,我不想让他们同时使用这两种状态。

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

【问题讨论】:

  • 为什么不使用重载?定义一种采用int 的方法和一种采用string?
  • 你能把它作为答案吗?我完全忘记了超载!谢谢!

标签: c# optional-parameters


【解决方案1】:

为什么不重载

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
}

【讨论】:

    【解决方案2】:

    可能会创建两个重载的方法,比如

     public void DoThing (string bar, int foo = 0){
    // code here
     }
    
     public void DoThing (int foo , string bar = "test"){
    // code here
     }
    

    【讨论】:

    • 可选参数应该是最后一个
    • @Badulake 不错 .. 谢谢
    猜你喜欢
    • 2018-08-04
    • 2021-04-11
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2010-12-21
    • 2012-02-22
    • 1970-01-01
    相关资源
    最近更新 更多