gpt4 book ai didi

c# - 当 7 个 bool 值中有 3 个计算为真时如何调用函数

转载 作者:行者123 更新时间:2023-12-04 00:20:42 25 4
gpt4 key购买 nike

我正在尝试以这种方式创建一个任务给予系统:

有 7 个 bool 值和一个方法,仅当 7 个 bool 值中的任何 3 个计算结果为真时才应调用该方法。完成这项任务最有效/更好的方法是什么?我对编程有点陌生,所以这是一个代码片段:

private bool a;
private bool b;
private bool c;
private bool d;
private bool e;
private bool f;
private bool g;

private void Start() {
//How do I call TheMethod() when any 3 of the 7 booleans evaluates to true?
}

private void TheMethod() {
//DO SOMETHING
}

我是否必须创建多个 if 条件来检查它?

最佳答案

在 Linq 中使用数组或列表可以简化您的测试:

using System.Linq;
using System.Collections.Generic;

// using array a = trig[0], b = trig[1] and so on
private bool[] trig = new bool[7] { true, false, false, true, true, false, true };

//or using list a = trig1[0], b = trig1[1] and so on
private List<bool> trig1 = new List<bool>{ true, false, false, true, true, false, true };


void Start(){
//same syntax array or list
trig[0] = false; // change value for fun
if(trig.Count(p => p) ==3)// result = 3
{
TheMethod();
}

trig1[0] = false;// change value for fun
if(trig1.Count(p => p) ==3) //result = 3
{
TheMethod();
}


//if you want to keep your boolean variable outside a collection
//you add your boolean variables to list (or array)
var list = new List<Bool>() {a,b,c,d,e,f,g};
if (list.Count(p => p) == 3)
{
TheMethod();
}
}

关于c# - 当 7 个 bool 值中有 3 个计算为真时如何调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60927783/

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