gpt4 book ai didi

c# - 在 C# 中有条件地传递可选参数

转载 作者:太空宇宙 更新时间:2023-11-03 22:43:21 25 4
gpt4 key购买 nike

我有一个函数有超过 10 个可选参数,我在我的程序中有设置来确定是否应该传递一个参数。例如,

public void MyFunction(bool? b1=null, bool? b2=null, bool? b3=null.. bool? b10=null)

以下是指示是否应设置参数的设置

bool setb1 = false;
bool setb2 = false;
bool setb3 = true;
bool setb4 = false;
bool setb5 = true;

如果我要按照设置来设置参数,那么我将不得不做这样的事情

if (!setb1 && !setb2 && !setb4)
MyFunction(b3: value3, b5: value5);

如果我有10个设置和10个参数,那么我的组合就会太多,所以我认为我的实现是不可行的。实现此目标的正确方法是什么?

最佳答案

你的函数有一个 Long Parameter List

我会传递一个对象作为参数,创建一个类 ConditionModle

你可以在这个类中封装你想要的条件。

public class ConditionModle
{
public bool setb1 { get; set; }
public bool setb2 { get; set; }
public bool setb3 { get; set; }
public bool setb4 { get; set; }
public bool setb5 { get; set; }
....
public bool Condition1()
{
return !this.setb1 && !this.setb2 && !this.setb4;
}
}

if (model.Condition1())
MyFunction(model);

此解决方案可以帮助您编写代码

  1. 更清晰,
  2. 增加新的属性或判断方法,不会影响之前的方法。
  3. 添加新属性,您不会修改调用方法参数。

关于c# - 在 C# 中有条件地传递可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51160329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com