[英]If you have multiple variables with different values and i want to pass these values through a block of code that process the value,how do i do that?
This is a hypothetical scenario, but lets say that 这是一个假设的场景,但可以说
int age1 = 12, age2=3, age3=7
I want to pass each of these variable to through a block of code that tells me whether or not it the age is greater then 10. 我想将每个变量传递给一个代码块,该代码块告诉我年龄是否大于10岁。
Is there a way to do that without loops and writing a whole bunch of if statements. 有没有一种方法可以做到这一点而无需循环并编写大量的if语句。 (If I have to write 1 if statement that is fine, but not multiple ones)
(如果我必须写1个if语句很好,但不能多个)
As a generalized solution, you can try params
and Linq ( Any
): 作为通用解决方案,您可以尝试使用
params
和Linq ( Any
):
static bool HasGreaterThan10(params int[] ages) {
return ages.Any(age => age > 10);
}
Example 例
if (HasGreaterThan10(12, 3, 7)) {
...
}
If you want to test if all the ages are greater then 10
use All
: 如果要测试所有年龄是否都大于
10
使用All
:
static bool AllGreaterThan10(params int[] ages) {
return ages.All(age => age > 10);
}
...
if (AllGreaterThan10(age1, age2, age3, age4)) {
...
}
You can declare the array locally and get rid of method if you want: 您可以在本地声明数组,并在需要时放弃方法:
if (new int[] {age1, age2, age3}.Any(age => age > 10)) {
...
}
The concept you are looking for is called arrays . 您正在寻找的概念称为数组 。
And looping over an array is always preferred over writing code that names things a1, a2, a3, ... and that then explicitly deals with all those values. 并且始终优先于遍历数组而不是编写代码来命名事物a1,a2,a3,...,然后显式处理所有这些值。
The point is: maybe you think that those values will do today, but thing is: there is a certain chance that you will have to use 4 values tomorrow. 关键是:也许您认为这些值将在今天使用,但事实是:明天您很有可能必须使用4个值。 And 7 the other week.
还有7个星期。
You can use the "or else" operator ( ||
) 您可以使用“或其他”运算符(
||
)
bool isGreater(int age1, int age2, int age3) {
return (age1>10) || (age2>10) || (age3>10);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.