用于检查具有多个值的相等性的语法糖

her*_*dev 3 .net c# equality

我想compare 2 equations,让我们说2*2 and 2+2一个答案4,使用Visual Studio 2015,例如

if (4 == (2*2 && 2+2)) {...}
Run Code Online (Sandbox Code Playgroud)

但它返回一个错误,"运算符'&&'不能应用于'int'和'int'类型的操作数." 我能想到编写代码的唯一方法是:

if (4 == 2*2 && 4 == 2+2) {...}
Run Code Online (Sandbox Code Playgroud)

哪个会起作用,但是当要比较很多值时会变得非常重复.有没有更简单的方法来实现这一目标?

Asi*_*sik 11

var results = new[]{ 2 + 2, 2 * 2, ... };
if (results.All(r => r == 4)) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

这将收集集合中所有操作的结果results,并使用扩展方法All验证指定的谓词是否适用于所有值; 允许只编写一次谓词.


pok*_*oke 5

你可以写一个函数:

public static bool AllEqual<T>(T expectedResult, params T[] calculations)
    where T : IEquatable<T>
{
    return calculations.All(x => x.Equals(expectedResult));
}
Run Code Online (Sandbox Code Playgroud)

例如:

if (AllEqual(4, 2 + 2, 2 * 2, 1 + 1 + 1 + 1)) {
    // true
}

if (AllEqual(4, 2 + 2, 2 * 3)) {
    // not true
}
Run Code Online (Sandbox Code Playgroud)

这甚至适用于其他类型,例如

if (AllEqual("foo", "f" + "o" + "o", "fooo".Substring(0, 3))) {
    // true
}
Run Code Online (Sandbox Code Playgroud)