c# - 你能有带有限制条件的可选参数吗?
问题描述
我想创建一个有两个可选参数的函数,但你只能选择两个可选参数之一。
例如:
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!");
,它将调用这两种状态,我不想让他们同时使用这两种状态。
是否可以强制他们在编译代码之前修复这个错误?
解决方案
为什么不超载?
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
}
推荐阅读
- spring - 如何在春季动态执行验证?
- android - 如何测试自定义视图性能
- python - 检查输入时出错:预期 input_18 有 3 个维度,但得到了形状为 (7, 210) 的数组
- android - 展开时折叠工具栏标题之间的额外空间
- linux - 多个用户的 Linux 用户权限文件夹
- javascript - 卡在搜索 js 上
- flutter - 当参数传递颤振时,构建函数在 dispose 之前被调用
- php - 准备好的语句不在 PHP 中执行,但可以在 SQL 控制台上完美运行
- cordova - 如何将 Cordova 插件暴露给 Svelte 应用程序?
- java - 在 Postgresql 进程被杀死后,Spring 无法回滚 JDBC 连接